Filestream和Byte[]之间的转换
Code
1using System;
2using System.IO;
3using System.IO.Compression;
4
5public class DeflateTest
6{
7 //读filename到byte[]
8 public static byte[] ReadFile(string fileName)
9 {
10 FileStream fs = new FileStream(fileName,FileMode.OpenOrCreate);
11 byte[] buffer = new byte[fs.Length];
12 try
13 {
14 fs.Read(buffer, 0, buffer.Length);
15 fs.Seek(0, SeekOrigin.Begin);
16 return buffer;
17 }
18 catch
19 {
20 return buffer;
21 }
22 finally
23 {
24 if (fs != null)
25 fs.Close();
26 }
27 }
28 //写byte[]到fileName
29 public static bool WriteFile(byte[] pReadByte, string fileName)
30 {
31 FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate);
32 try
33 {
34 fs.Write(pReadByte, 0, pReadByte.Length);
35 }
36 catch
37 {
38 return false;
39 }
40 finally
41 {
42 if (fs != null)
43 fs.Close();
44 }
45 return true;
46 }
47
48
49 public static void Main(string[] args)
50 {
51 byte[] b = ReadFile(@"d:/a.jpg");
52 if (WriteFile(b, @"d:/a3.jpg"))
53 {
54 Console.WriteLine("Success");
55 }
56 else
57 {
58 Console.WriteLine("Sorry");
59 }
60 Console.ReadLine();
61 }
62}
63
1using System;
2using System.IO;
3using System.IO.Compression;
4
5public class DeflateTest
6{
7 //读filename到byte[]
8 public static byte[] ReadFile(string fileName)
9 {
10 FileStream fs = new FileStream(fileName,FileMode.OpenOrCreate);
11 byte[] buffer = new byte[fs.Length];
12 try
13 {
14 fs.Read(buffer, 0, buffer.Length);
15 fs.Seek(0, SeekOrigin.Begin);
16 return buffer;
17 }
18 catch
19 {
20 return buffer;
21 }
22 finally
23 {
24 if (fs != null)
25 fs.Close();
26 }
27 }
28 //写byte[]到fileName
29 public static bool WriteFile(byte[] pReadByte, string fileName)
30 {
31 FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate);
32 try
33 {
34 fs.Write(pReadByte, 0, pReadByte.Length);
35 }
36 catch
37 {
38 return false;
39 }
40 finally
41 {
42 if (fs != null)
43 fs.Close();
44 }
45 return true;
46 }
47
48
49 public static void Main(string[] args)
50 {
51 byte[] b = ReadFile(@"d:/a.jpg");
52 if (WriteFile(b, @"d:/a3.jpg"))
53 {
54 Console.WriteLine("Success");
55 }
56 else
57 {
58 Console.WriteLine("Sorry");
59 }
60 Console.ReadLine();
61 }
62}
63