用数据流处理文件-文件读取到MemoryStream中和MemoryStream写入到文件

This code writes down MemoryStream to a file:

FileStream file =newFileStream("file.bin",FileMode.Create,System.IO.FileAccess.Write);
byte[] bytes =newbyte[ms.Length];
ms.Read(bytes,0,(int)ms.Length);
file.Write(bytes,0, bytes.Length);
file.Close();
ms.Close();

and this reads a file to a MemoryStream :
MemoryStream ms =newMemoryStream();
FileStream file =newFileStream("file.bin",FileMode.Create,FileAccess.Read);
byte[] bytes =newbyte[file.Length];
file.Read(bytes,0,(int)file.Length);
ms.Write(bytes,0,(int)file.Length);
file.Close();
ms.Close();

例子:
Stream fileStream = File.OpenRead("d:\\pp23.xls");

                //FileStream fileStream = new FileStream("d:\\pp23.xls", FileMode.Open);
                FileStream fs = new FileStream("D:\\pp23_1.xls", FileMode.Create);

                
                byte[] buffer = new byte[10000];
                Stream outputStream = new MemoryStream(); 
                int sourceBytes;
                int i = 1;
                do
                {
                    sourceBytes = fileStream.Read(buffer, 0, buffer.Length);
                    if (i == 0)
                    {
                        foreach (byte b in buffer)
                        {
                            Console.WriteLine(b);
                        }
                    }
                    i += 1;
                    //文件写入到流中
                    if (sourceBytes != 0)
                    {
                        outputStream.Write(buffer, 0, sourceBytes);
                    }
                    //直接写入FileStream中
                    //fs.Write(buffer, 0, buffer.Length);
                    
                }
                while (sourceBytes > 0);

                //文件写入到流中
                byte[] bytes = new byte[outputStream.Length];
//从开始位置读取
          outputStream.Position = 0; outputStream.Read(bytes,
0, (int)outputStream.Length); fs.Write(bytes, 0, bytes.Length); fs.Close(); fileStream.Close(); outputStream.Close();

 

 

 

你可能感兴趣的:(Stream)