文件转换成二进制字符串写入HTTP输出流
1 protected void Page_Load(object sender, EventArgs e)
2 {
3 try
4 {
5 string path = "Tett.PDF"; //获取文件名
6 path = Server.MapPath(path); //获取物理文件路径
7 if (File.Exists(path) == false)
8 throw new Exception("找不到PDF文件");
9 FileStream fs = File.Open(path, FileMode.Open);
10 byte[] buffer = new byte[fs.Length];
11 fs.Read(buffer, 0, buffer.Length);
12 fs.Close();
13 Response.ContentType = "application/pdf";
14 Response.AddHeader("content-disposition", "filename=pdf");
15 Response.AddHeader("content-length", buffer.Length.ToString());
16 Response.BinaryWrite(buffer);
17 }
18 catch (Exception exp)
19 {
20 throw new Exception("错误", exp);
21 }
22 finally
23 {
24 Response.Flush();
25 Response.Close();
26 Response.End();
27 }
28
获取HTTP传入的实体内容保存文件
1 string path = "Test.PDF";
2 path = Server.MapPath(path);
3 if (File.Exists(path) == false)
4 throw new Exception("找不到PDF文件");
5 using (var inputStream = Request.InputStream)
6 {
7 using (var flieStream = new FileStream(path, FileMode.Create))
8 {
9 //从当前流中读取所有字节并将其写入到目标流中
10 inputStream.CopyTo(flieStream);
11 }
12
二进制转换成
/// <summary>
2 /// 二进制转换成
3 /// </summary>
4 /// <param name="Bytes"></param>
5 /// <returns></returns>
6 public static Bitmap BytesToBitmap(byte[] Bytes)
7 {
8 MemoryStream stream = null;
9 try
10 {
11 stream = new MemoryStream(Bytes);
12 return new Bitmap((Image)new Bitmap(stream));
13 }
14 catch (ArgumentNullException ex)
15 {
16 throw ex;
17 }
18 catch (ArgumentException ex)
19 {
20 throw ex;
21 }
22 finally
23 {
24 stream.Close();
25 }
26 }
1 /// <summary>
2 /// 转换成二进制
3 /// </summary>
4 /// <param name="Bitmap"></param>
5 /// <returns></returns>
6 public static byte[] BitmapToBytes(Bitmap Bitmap)
7 {
8 MemoryStream ms = null;
9 try
10 {
11 ms = new MemoryStream();
12 Bitmap.Save(ms, Bitmap.RawFormat);
13 byte[] byteImage = new Byte[ms.Length];
14 byteImage = ms.ToArray();
15 return byteImage;
16 }
17 catch (ArgumentNullException ex)
18 {
19 throw ex;
20 }
21 finally
22 {
23 ms.Close();
24 }
25 }
流转换成文件
1 using (FileStream fs = new FileStream(path, FileMode.Create))
2 {
3 byte[] bytes = new byte[stream.Length];
4 int numBytesRead = 0;
5 int numBytesToRead = (int)stream.Length;
6 stream.Position = 0;
7 while (numBytesToRead > 0)
8 {
9 int n = stream.Read(bytes, numBytesRead, Math.Min(numBytesToRead, int.MaxValue));
10 if (n <= 0)
11 {
12 break;
13 }
14 fs.Write(bytes, numBytesRead, n);
15 numBytesRead += n;
16 numBytesToRead -= n;
17 }
18 fs.Close();
19 }
文件转换成流
1 /// <summary>
2 /// 从文件读取 Stream
3 /// </summary>
4 public Stream FileToStream(string fileName)
5 {
6 // 打开文件
7 FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
8 // 读取文件的 byte[]
9 byte[] bytes = new byte[fileStream.Length];
10 fileStream.Read(bytes, 0, bytes.Length);
11 fileStream.Close();
12 // 把 byte[] 转换成 Stream
13 Stream stream = new MemoryStream(bytes);
14 return stream;
15 }