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

 

 

 

posted on 2012-08-01 17:33  Black Bean  阅读(15120)  评论(1编辑  收藏  举报