c# 读文件成二进制流 把二进制流下载成文件

本文介绍了如何使用C#将文件读取为二进制流并保存到byte数组中,同时展示了如何从数据库获取二进制文件数据并将其作为文件提供给用户下载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 读文件成二进制流保存到byte数组bufferFile 
 string myComputerFilePath = "E:\\noticeFujian\\20150506\\6356652772708821699019939.txt"; //文件路径
//读文件成二进制流
 FileStream stream = new FileInfo(myComputerFilePath).OpenRead();
 var bufferLength = stream.Length;
 byte[] bufferFile = new byte[bufferLength];
 stream.Read(bufferFile, 0, Convert.ToInt32(bufferLength));


2.把二进制流下载成文件
         
string conStr = "Server=.;Database=testDB;user id=sa;password=password;";
            SqlConnection sqlconnection = new SqlConnection(conStr);
            SqlCommand scom = new SqlCommand();
            scom.CommandText = "select ByteData,FileName,Size from [TB_myTab] where ID ='25171b44-3422-4e11-ad98-8250a7ad3cf9'";
            scom.Connection = sqlconnection;
            scom.Connection.Open();
            SqlDataReader dr = scom.ExecuteReader();
            dr.Read();

            int fileDataCol = 0;
            Byte[] b = new Byte[(dr.GetBytes(fileDataCol, 0, null, 0, int.MaxValue))];
            string filename = Server.UrlEncode(dr.GetString(1));
            
            dr.GetBytes(fileDataCol, 0, b, 0, b.Length);
            dr.Close();
            sqlconnection.Close();

            Response.ContentType = "Application/plain";             
            Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
            this.Response.Clear();
            System.IO.Stream fs = this.Response.OutputStream;
            fs.Write(b, 0, b.Length);
            fs.Close();
            this.Response.End();


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值