zoukankan      html  css  js  c++  java
  • 用数据流处理文件文件读取到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();

     

     

  • 相关阅读:
    python基础之函数
    MySQL 安装 5.0
    MySQL安装 MySQL5.7.10免安装版配置,mysql5.7.10免安装版
    安装MYSql Windows7下MySQL5.5.20免安装版的配置
    网站集合
    andorid 开放工具集合
    Win7 x64 Eclipse无法识别手机 / adb interface有黄色感叹号,无法识别
    字符集 ISO-8859-1(3)
    字符集 ISO-8859-1(2)
    字符集 ISO-8859-1(1)
  • 原文地址:https://www.cnblogs.com/blackbean/p/2618714.html
Copyright © 2011-2022 走看看