当前位置: 开源爱好者 » 编程教程 » C#教程 » 正文

C# 读写文件流切分组合文件

C# 文件读写操作实例,读写文件流切分组合文件,通过代码你就能看明白,本代码是一个按钮的单击事件处理程序,当用户在C#的WinForm窗体中单击按钮后,即执行下列函数中的代码,供测试的文件内容取自mdb数据库,你可以修改为其它的测试数据库:

private void button4_Click(object sender, EventArgs e)
{//读写文件流切分组合文件
    var MyFileName = "F:\\Northwind.mdb";
    var MyFileInfo = new System.IO.FileInfo(MyFileName);
    var MyFileSize = MyFileInfo.Length;
    var MySubSize = 1440000;
    var MyCount = (int)System.Math.Ceiling(Double.Parse(MyFileSize.ToString()) / Double.Parse(MySubSize.ToString()));
    var MyInFile = new System.IO.FileStream(MyFileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Read);
    for (var i = 0; i < MyCount; i++)
    {
        var MyOutFile = new System.IO.FileStream(MyFileName + i + ".xyz", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
        var data = 0;
        byte[] buffer = new byte[MySubSize];
        if ((data = MyInFile.Read(buffer, 0, MySubSize)) > 0)
           MyOutFile.Write(buffer, 0, data);
        MyOutFile.Close();
    }
    MyInFile.Close();
    MessageBox.Show("切分文件操作完成!", "信息提示", MessageBoxButtons.OK);
    var MyCombineFile = "F:\\NewNorthwind.mdb";
    var MyNewOutFile = new System.IO.FileStream(MyCombineFile, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
    for (var i = 0; i < MyCount; i++)
    {
       var data = 0;
       byte[] buffer = new byte[1024];
       var MyNewInFile = new System.IO.FileStream(MyFileName + i + ".xyz", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Read);
       while ((data = MyNewInFile.Read(buffer, 0, 1024)) > 0)
           MyNewOutFile.Write(buffer, 0, data);
       MyNewInFile.Close();
    }
    MyNewOutFile.Close();
    MessageBox.Show("组合文件操作完成", "信息提示", MessageBoxButtons.OK);            
}
private void button5_Click(object sender, EventArgs e)
{//压缩文件
    var MySourceFile = "F:\\Northwind.mdb";
    var MyDestinationFile = "C:\\NW.arj";
    if (System.IO.File.Exists(MySourceFile) == false)
        return;
    byte[] MyBuffer = null;
    var MySourceStream = new System.IO.FileStream(MySourceFile, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
    MyBuffer = new byte[MySourceStream.Length];
    MySourceStream.Read(MyBuffer, 0, MyBuffer.Length);
    var MyDestinationStream = new System.IO.FileStream(MyDestinationFile, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
    var MyCompressedStream = new System.IO.Compression.GZipStream(MyDestinationStream, System.IO.Compression.CompressionMode.Compress, true);
    MyCompressedStream.Write(MyBuffer, 0, MyBuffer.Length);
    MessageBox.Show("压缩大尺寸文件顺利完成!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
    if (MySourceStream != null)
      MySourceStream.Close();
    if (MyCompressedStream != null)
      MyCompressedStream.Close();
    if (MyDestinationStream != null)
      MyDestinationStream.Close();            
}

 

CopyRight 2018© 开源爱好者 All Rights Reserved 豫ICP备16030607号 隐私声明 网站地图