C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C#文件分割 合并

C#实现文件分割和合并的示例详解

作者:芝麻粒儿

这篇文章主要为大家详细介绍了如何利用C#实现文件分割和合并的功能,文中的示例代码讲解详细,对我们学习C#有一定的帮助,感兴趣的小伙伴可以跟随小编一起了解一下

实践过程

效果

代码

public partial class frmSplit : Form
{
    public frmSplit()
    {
        InitializeComponent();
    }

    #region 分割文件
    /// <summary>
    /// 分割文件
    /// </summary>
    /// <param name="strFlag">分割单位</param>
    /// <param name="intFlag">分割大小</param>
    /// <param name="strPath">分割后的文件存放路径</param>
    /// <param name="strFile">要分割的文件</param>
    /// <param name="PBar">进度条显示</param>
    public void SplitFile(string strFlag, int intFlag, string strPath, string strFile, ProgressBar PBar)
    {
        int iFileSize = 0;
        //根据选择来设定分割的小文件的大小
        switch (strFlag)
        {
            case "Byte":
                iFileSize = intFlag;
                break;
            case "KB":
                iFileSize = intFlag * 1024;
                break;
            case "MB":
                iFileSize = intFlag * 1024 * 1024;
                break;
            case "GB":
                iFileSize = intFlag * 1024 * 1024 * 1024;
                break;
        }
        //以文件的全路径对应的字符串和文件打开模式来初始化FileStream文件流实例
        FileStream SplitFileStream = new FileStream(strFile, FileMode.Open);
        //以FileStream文件流来初始化BinaryReader文件阅读器
        BinaryReader SplitFileReader = new BinaryReader(SplitFileStream);
        //每次分割读取的最大数据
        byte[] TempBytes;
        //小文件总数
        int iFileCount = (int)(SplitFileStream.Length / iFileSize);
        PBar.Maximum = iFileCount;
        if (SplitFileStream.Length % iFileSize != 0) iFileCount++;
        string[] TempExtra = strFile.Split('.');
        //循环将大文件分割成多个小文件
        for (int i = 1; i <= iFileCount; i++)
        {
            //确定小文件的文件名称
            string sTempFileName = strPath + @"\" + i.ToString().PadLeft(4, '0') + "." + TempExtra[TempExtra.Length - 1]; //小文件名
            //根据文件名称和文件打开模式来初始化FileStream文件流实例
            FileStream TempStream = new FileStream(sTempFileName, FileMode.OpenOrCreate);
            //以FileStream实例来创建、初始化BinaryWriter书写器实例
            BinaryWriter TempWriter = new BinaryWriter(TempStream);
            //从大文件中读取指定大小数据
            TempBytes = SplitFileReader.ReadBytes(iFileSize);
            //把此数据写入小文件
            TempWriter.Write(TempBytes);
            //关闭书写器,形成小文件
            TempWriter.Close();
            //关闭文件流
            TempStream.Close();
            PBar.Value = i - 1;
        }
        //关闭大文件阅读器
        SplitFileReader.Close();
        SplitFileStream.Close();
        MessageBox.Show("文件分割成功!");
    }
    #endregion

    #region 合并文件
    /// <summary>
    /// 合并文件
    /// </summary>
    /// <param name="list">要合并的文件集合</param>
    /// <param name="strPath">合并后的文件名称</param>
    /// <param name="PBar">进度条显示</param>
    public void CombinFile(string[] strFile, string strPath, ProgressBar PBar)
    {
        PBar.Maximum = strFile.Length;
        FileStream AddStream = null;
        //以合并后的文件名称和打开方式来创建、初始化FileStream文件流
        AddStream = new FileStream(strPath, FileMode.Append);
        //以FileStream文件流来初始化BinaryWriter书写器,此用以合并分割的文件
        BinaryWriter AddWriter = new BinaryWriter(AddStream);
        FileStream TempStream = null;
        BinaryReader TempReader = null;
        //循环合并小文件,并生成合并文件
        for (int i = 0; i < strFile.Length; i++)
        {
            //以小文件所对应的文件名称和打开模式来初始化FileStream文件流,起读取分割作用
            TempStream = new FileStream(strFile[i].ToString(), FileMode.Open);
            TempReader = new BinaryReader(TempStream);
            //读取分割文件中的数据,并生成合并后文件
            AddWriter.Write(TempReader.ReadBytes((int)TempStream.Length));
            //关闭BinaryReader文件阅读器
            TempReader.Close();
            //关闭FileStream文件流
            TempStream.Close();
            PBar.Value = i + 1;
        }
        //关闭BinaryWriter文件书写器
        AddWriter.Close();
        //关闭FileStream文件流
        AddStream.Close();
        MessageBox.Show("文件合并成功!");
    }
    #endregion

    private void frmSplit_Load(object sender, EventArgs e)
    {
        timer1.Start();//启动计时器
    }

    //选择要分割的文件
    private void btnSFile_Click(object sender, EventArgs e)
    {
        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
            txtFile.Text = openFileDialog.FileName;
        }
    }

    //执行文件分割操作
    private void btnSplit_Click(object sender, EventArgs e)
    {
        try
        {
            if (txtLength.Text == ""||txtFile.Text.Trim()==""||txtPath.Text.Trim()=="")
            {
                MessageBox.Show("请将信息填写完整!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtLength.Focus();
            }
            else if (cboxUnit.Text == "")
            {
                MessageBox.Show("请选择要分割的文件单位!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                cboxUnit.Focus();
            }
            else
            {
                SplitFile(cboxUnit.Text, Convert.ToInt32(txtLength.Text.Trim()), txtPath.Text, txtFile.Text, progressBar);
            }
        }
        catch { }
    }

    //选择分割后的文件存放路径
    private void btnSPath_Click(object sender, EventArgs e)
    {
        if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
        {
            txtPath.Text = folderBrowserDialog.SelectedPath;
        }
    }

    //选择要合成的文件
    private void btnCFile_Click(object sender, EventArgs e)
    {
        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
            string Selectfile = "";
            string[] files = openFileDialog.FileNames;
            for (int i = 0; i < files.Length; i++)
            {
                Selectfile += "," + files[i].ToString();
            }
            if (Selectfile.StartsWith(","))
            {
                Selectfile = Selectfile.Substring(1);
            }
            if (Selectfile.EndsWith(","))
            {
                Selectfile.Remove(Selectfile.LastIndexOf(","),1);
            }
            txtCFile.Text = Selectfile;
        }
    }

    //选择合成后的文件存放路径
    private void btnCPath_Click(object sender, EventArgs e)
    {
        if (saveFileDialog.ShowDialog() == DialogResult.OK)
        {
            txtCPath.Text = saveFileDialog.FileName;
        }
    }

    //执行合成文件操作
    private void btnCombin_Click(object sender, EventArgs e)
    {
        try
        {
            if (txtCFile.Text.Trim() == "" || txtCPath.Text.Trim() == "")
            {
                MessageBox.Show("请将信息输入完整!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                if (txtCFile.Text.IndexOf(",") == -1)
                    MessageBox.Show("请选择要合成的文件,最少为两个!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                else
                {
                    string[] strFiles = txtCFile.Text.Split(',');
                    CombinFile(strFiles, txtCPath.Text, progressBar);
                }
            }
        }
        catch { }
    }

    //监视“分割”/“合并”按钮的可用状态
    private void timer1_Tick(object sender, EventArgs e)
    {
        if (txtFile.Text != "" && txtPath.Text != "")
            btnSplit.Enabled = true;
        else
            btnSplit.Enabled = false;
        if (txtCFile.Text != "" && txtCPath.Text != "")
            btnCombin.Enabled = true;
        else
            btnCombin.Enabled = false;
    }
}
partial class frmSplit
{
    /// <summary>
    /// 必需的设计器变量。
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// 清理所有正在使用的资源。
    /// </summary>
    /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows 窗体设计器生成的代码

    /// <summary>
    /// 设计器支持所需的方法 - 不要
    /// 使用代码编辑器修改此方法的内容。
    /// </summary>
    private void InitializeComponent()
    {
        this.components = new System.ComponentModel.Container();
        this.tabControl1 = new System.Windows.Forms.TabControl();
        this.tabPage1 = new System.Windows.Forms.TabPage();
        this.txtPath = new System.Windows.Forms.TextBox();
        this.txtLength = new System.Windows.Forms.TextBox();
        this.btnSPath = new System.Windows.Forms.Button();
        this.label3 = new System.Windows.Forms.Label();
        this.cboxUnit = new System.Windows.Forms.ComboBox();
        this.label2 = new System.Windows.Forms.Label();
        this.btnSplit = new System.Windows.Forms.Button();
        this.btnSFile = new System.Windows.Forms.Button();
        this.txtFile = new System.Windows.Forms.TextBox();
        this.label1 = new System.Windows.Forms.Label();
        this.tabPage2 = new System.Windows.Forms.TabPage();
        this.txtCPath = new System.Windows.Forms.TextBox();
        this.txtCFile = new System.Windows.Forms.TextBox();
        this.label5 = new System.Windows.Forms.Label();
        this.btnCPath = new System.Windows.Forms.Button();
        this.btnCombin = new System.Windows.Forms.Button();
        this.btnCFile = new System.Windows.Forms.Button();
        this.label4 = new System.Windows.Forms.Label();
        this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
        this.folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
        this.timer1 = new System.Windows.Forms.Timer(this.components);
        this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
        this.progressBar = new System.Windows.Forms.ProgressBar();
        this.tabControl1.SuspendLayout();
        this.tabPage1.SuspendLayout();
        this.tabPage2.SuspendLayout();
        this.SuspendLayout();
        // 
        // tabControl1
        // 
        this.tabControl1.Controls.Add(this.tabPage1);
        this.tabControl1.Controls.Add(this.tabPage2);
        this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill;
        this.tabControl1.Location = new System.Drawing.Point(0, 0);
        this.tabControl1.Name = "tabControl1";
        this.tabControl1.SelectedIndex = 0;
        this.tabControl1.Size = new System.Drawing.Size(354, 201);
        this.tabControl1.TabIndex = 0;
        // 
        // tabPage1
        // 
        this.tabPage1.Controls.Add(this.txtPath);
        this.tabPage1.Controls.Add(this.txtLength);
        this.tabPage1.Controls.Add(this.btnSPath);
        this.tabPage1.Controls.Add(this.label3);
        this.tabPage1.Controls.Add(this.cboxUnit);
        this.tabPage1.Controls.Add(this.label2);
        this.tabPage1.Controls.Add(this.btnSplit);
        this.tabPage1.Controls.Add(this.btnSFile);
        this.tabPage1.Controls.Add(this.txtFile);
        this.tabPage1.Controls.Add(this.label1);
        this.tabPage1.Location = new System.Drawing.Point(4, 21);
        this.tabPage1.Name = "tabPage1";
        this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
        this.tabPage1.Size = new System.Drawing.Size(346, 176);
        this.tabPage1.TabIndex = 0;
        this.tabPage1.Text = "文件分割";
        this.tabPage1.UseVisualStyleBackColor = true;
        // 
        // txtPath
        // 
        this.txtPath.Location = new System.Drawing.Point(37, 117);
        this.txtPath.Name = "txtPath";
        this.txtPath.Size = new System.Drawing.Size(256, 21);
        this.txtPath.TabIndex = 10;
        // 
        // txtLength
        // 
        this.txtLength.Location = new System.Drawing.Point(37, 72);
        this.txtLength.Name = "txtLength";
        this.txtLength.Size = new System.Drawing.Size(146, 21);
        this.txtLength.TabIndex = 9;
        // 
        // btnSPath
        // 
        this.btnSPath.Location = new System.Drawing.Point(299, 115);
        this.btnSPath.Name = "btnSPath";
        this.btnSPath.Size = new System.Drawing.Size(37, 23);
        this.btnSPath.TabIndex = 8;
        this.btnSPath.Text = "<<";
        this.btnSPath.UseVisualStyleBackColor = true;
        this.btnSPath.Click += new System.EventHandler(this.btnSPath_Click);
        // 
        // label3
        // 
        this.label3.AutoSize = true;
        this.label3.Location = new System.Drawing.Point(12, 100);
        this.label3.Name = "label3";
        this.label3.Size = new System.Drawing.Size(137, 12);
        this.label3.TabIndex = 7;
        this.label3.Text = "选择分割后文件存放路径";
        // 
        // cboxUnit
        // 
        this.cboxUnit.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
        this.cboxUnit.FormattingEnabled = true;
        this.cboxUnit.Items.AddRange(new object[] {
        "Byte",
        "KB",
        "MB",
        "GB"});
        this.cboxUnit.Location = new System.Drawing.Point(189, 73);
        this.cboxUnit.Name = "cboxUnit";
        this.cboxUnit.Size = new System.Drawing.Size(63, 20);
        this.cboxUnit.TabIndex = 6;
        // 
        // label2
        // 
        this.label2.AutoSize = true;
        this.label2.Location = new System.Drawing.Point(12, 55);
        this.label2.Name = "label2";
        this.label2.Size = new System.Drawing.Size(101, 12);
        this.label2.TabIndex = 5;
        this.label2.Text = "设置分割文件大小";
        // 
        // btnSplit
        // 
        this.btnSplit.Location = new System.Drawing.Point(261, 26);
        this.btnSplit.Name = "btnSplit";
        this.btnSplit.Size = new System.Drawing.Size(75, 23);
        this.btnSplit.TabIndex = 3;
        this.btnSplit.Text = "分割";
        this.btnSplit.UseVisualStyleBackColor = true;
        this.btnSplit.Click += new System.EventHandler(this.btnSplit_Click);
        // 
        // btnSFile
        // 
        this.btnSFile.Location = new System.Drawing.Point(220, 26);
        this.btnSFile.Name = "btnSFile";
        this.btnSFile.Size = new System.Drawing.Size(40, 23);
        this.btnSFile.TabIndex = 2;
        this.btnSFile.Text = "<<";
        this.btnSFile.UseVisualStyleBackColor = true;
        this.btnSFile.Click += new System.EventHandler(this.btnSFile_Click);
        // 
        // txtFile
        // 
        this.txtFile.Location = new System.Drawing.Point(37, 27);
        this.txtFile.Name = "txtFile";
        this.txtFile.Size = new System.Drawing.Size(179, 21);
        this.txtFile.TabIndex = 1;
        // 
        // label1
        // 
        this.label1.AutoSize = true;
        this.label1.Location = new System.Drawing.Point(12, 10);
        this.label1.Name = "label1";
        this.label1.Size = new System.Drawing.Size(113, 12);
        this.label1.TabIndex = 0;
        this.label1.Text = "请选择要分割的文件";
        // 
        // tabPage2
        // 
        this.tabPage2.Controls.Add(this.txtCPath);
        this.tabPage2.Controls.Add(this.txtCFile);
        this.tabPage2.Controls.Add(this.label5);
        this.tabPage2.Controls.Add(this.btnCPath);
        this.tabPage2.Controls.Add(this.btnCombin);
        this.tabPage2.Controls.Add(this.btnCFile);
        this.tabPage2.Controls.Add(this.label4);
        this.tabPage2.Location = new System.Drawing.Point(4, 21);
        this.tabPage2.Name = "tabPage2";
        this.tabPage2.Padding = new System.Windows.Forms.Padding(3);
        this.tabPage2.Size = new System.Drawing.Size(346, 176);
        this.tabPage2.TabIndex = 1;
        this.tabPage2.Text = "文件合成";
        this.tabPage2.UseVisualStyleBackColor = true;
        // 
        // txtCPath
        // 
        this.txtCPath.Location = new System.Drawing.Point(37, 88);
        this.txtCPath.Name = "txtCPath";
        this.txtCPath.Size = new System.Drawing.Size(256, 21);
        this.txtCPath.TabIndex = 6;
        // 
        // txtCFile
        // 
        this.txtCFile.Location = new System.Drawing.Point(37, 44);
        this.txtCFile.Name = "txtCFile";
        this.txtCFile.Size = new System.Drawing.Size(174, 21);
        this.txtCFile.TabIndex = 5;
        // 
        // label5
        // 
        this.label5.AutoSize = true;
        this.label5.Location = new System.Drawing.Point(11, 72);
        this.label5.Name = "label5";
        this.label5.Size = new System.Drawing.Size(173, 12);
        this.label5.TabIndex = 4;
        this.label5.Text = "选择合并后文件存放路径及名称";
        // 
        // btnCPath
        // 
        this.btnCPath.Location = new System.Drawing.Point(299, 87);
        this.btnCPath.Name = "btnCPath";
        this.btnCPath.Size = new System.Drawing.Size(38, 23);
        this.btnCPath.TabIndex = 3;
        this.btnCPath.Text = "<<";
        this.btnCPath.UseVisualStyleBackColor = true;
        this.btnCPath.Click += new System.EventHandler(this.btnCPath_Click);
        // 
        // btnCombin
        // 
        this.btnCombin.Location = new System.Drawing.Point(262, 44);
        this.btnCombin.Name = "btnCombin";
        this.btnCombin.Size = new System.Drawing.Size(75, 23);
        this.btnCombin.TabIndex = 2;
        this.btnCombin.Text = "合并";
        this.btnCombin.UseVisualStyleBackColor = true;
        this.btnCombin.Click += new System.EventHandler(this.btnCombin_Click);
        // 
        // btnCFile
        // 
        this.btnCFile.Location = new System.Drawing.Point(217, 44);
        this.btnCFile.Name = "btnCFile";
        this.btnCFile.Size = new System.Drawing.Size(39, 23);
        this.btnCFile.TabIndex = 1;
        this.btnCFile.Text = "<<";
        this.btnCFile.UseVisualStyleBackColor = true;
        this.btnCFile.Click += new System.EventHandler(this.btnCFile_Click);
        // 
        // label4
        // 
        this.label4.AutoSize = true;
        this.label4.Location = new System.Drawing.Point(11, 28);
        this.label4.Name = "label4";
        this.label4.Size = new System.Drawing.Size(101, 12);
        this.label4.TabIndex = 0;
        this.label4.Text = "选择要合成的文件";
        // 
        // openFileDialog
        // 
        this.openFileDialog.Multiselect = true;
        // 
        // timer1
        // 
        this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
        // 
        // progressBar
        // 
        this.progressBar.Dock = System.Windows.Forms.DockStyle.Bottom;
        this.progressBar.Location = new System.Drawing.Point(0, 181);
        this.progressBar.Name = "progressBar";
        this.progressBar.Size = new System.Drawing.Size(354, 20);
        this.progressBar.TabIndex = 1;
        // 
        // frmSplit
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(354, 201);
        this.Controls.Add(this.progressBar);
        this.Controls.Add(this.tabControl1);
        this.MaximizeBox = false;
        this.MinimizeBox = false;
        this.Name = "frmSplit";
        this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
        this.Text = "文件分割与合成";
        this.Load += new System.EventHandler(this.frmSplit_Load);
        this.tabControl1.ResumeLayout(false);
        this.tabPage1.ResumeLayout(false);
        this.tabPage1.PerformLayout();
        this.tabPage2.ResumeLayout(false);
        this.tabPage2.PerformLayout();
        this.ResumeLayout(false);

    }

    #endregion

    public System.Windows.Forms.TabControl tabControl1;
    private System.Windows.Forms.TabPage tabPage1;
    private System.Windows.Forms.TextBox txtFile;
    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.TabPage tabPage2;
    private System.Windows.Forms.TextBox txtPath;
    private System.Windows.Forms.TextBox txtLength;
    private System.Windows.Forms.Button btnSPath;
    private System.Windows.Forms.Label label3;
    private System.Windows.Forms.ComboBox cboxUnit;
    private System.Windows.Forms.Label label2;
    private System.Windows.Forms.Button btnSplit;
    private System.Windows.Forms.Button btnSFile;
    private System.Windows.Forms.OpenFileDialog openFileDialog;
    private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog;
    private System.Windows.Forms.TextBox txtCPath;
    private System.Windows.Forms.TextBox txtCFile;
    private System.Windows.Forms.Label label5;
    private System.Windows.Forms.Button btnCPath;
    private System.Windows.Forms.Button btnCombin;
    private System.Windows.Forms.Button btnCFile;
    private System.Windows.Forms.Label label4;
    private System.Windows.Forms.Timer timer1;
    private System.Windows.Forms.SaveFileDialog saveFileDialog;
    private System.Windows.Forms.ProgressBar progressBar;
}

到此这篇关于C#实现文件分割和合并的示例详解的文章就介绍到这了,更多相关C#文件分割 合并内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文