关于“文件流”相关的(未完)

1.Stream转换成byte[]

byte[] bytes= new byte[stream.Length];

stream.Read(bytes,0,bytes.Length);

试验如下:

FileStream stream=File.OpenRead(@"C:\Users\Administrator\Desktop\1.txt");
//stream转byte[]
byte[] bytes = new byte[stream.Length];

stream.Read(bytes, 0, bytes.Length);
// stream.Seek(0, SeekOrigin.Begin); 试验中有没有这一行都行
string s= Encoding.UTF8.GetString(bytes);
Console.WriteLine(s);
Console.ReadKey();

 

2.把 byte[] 转换成 Stream 

 Stream stream = new MemoryStream(bytes); 

 return stream;

 

 3.byte[]转换成string

string s = System.Convert.ToBase64String(bytes);//第一种
string s= Encoding.Default.GetString(bytes);//第二种

4.string转换成byte[]

bytes = System.Convert.FromBase64String(s);//第一种

bytes = Encoding.Default.GetBytes(s);//第二种

5.读文件-流-写入文件

static void Main(string[] args)
        {
            using (FileStream stream = File.OpenRead(@"D:\c#\电子书\你必须知道的.NET.pdf"))
            // using (FileStream stream = new FileStream(@"D:\c#\电子书\你必须知道的.NET.pdf", FileMode.Open, FileAccess.Read))
             using ( FileStream s = new FileStream(@"D:\c#\电子书\1.pdf", FileMode.OpenOrCreate, FileAccess.Write))
            {
                byte[] bytes = new byte[1024 * 1024];
                int r;

                while ((r = stream.Read(bytes, 0, bytes.Length)) > 0)
                {
                    s.Write(bytes, 0, r);
                }
            }

            Console.WriteLine("ok");
            Console.ReadKey();
        }

 

posted @ 2016-08-31 15:21  JohnMarnoon  阅读(151)  评论(0编辑  收藏  举报