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

时间:2021-12-28 03:58:00

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();