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

.NET
316
0
0
2023-07-11
标签   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 =;
        //根据选择来设定分割的小文件的大小
        switch (strFlag)
        {
            case "Byte":
                iFileSize = intFlag;
                break;
            case "KB":
                iFileSize = intFlag *;
                break;
            case "MB":
                iFileSize = intFlag * * 1024;
                break;
            case "GB":
                iFileSize = intFlag * * 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 !=) iFileCount++;
        string[] TempExtra = strFile.Split('.');
        //循环将大文件分割成多个小文件
        for (int i =; i <= iFileCount; i++)
        {
            //确定小文件的文件名称
            string sTempFileName = strPath + @"\" + i.ToString().PadLeft(, '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 -;
        }
        //关闭大文件阅读器
        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 =; 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 +;
        }
        //关闭BinaryWriter文件书写器
        AddWriter.Close();
        //关闭FileStream文件流
        AddStream.Close();
        MessageBox.Show("文件合并成功!");
    }
    #endregion

    private void frmSplit_Load(object sender, EventArgs e)
    {
        timer.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.ToInt(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 =; i < files.Length; i++)
            {
                Selectfile += "," + files[i].ToString();
            }
            if (Selectfile.StartsWith(","))
            {
                Selectfile = Selectfile.Substring();
            }
            if (Selectfile.EndsWith(","))
            {
                Selectfile.Remove(Selectfile.LastIndexOf(","),);
            }
            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(",") == -)
                    MessageBox.Show("请选择要合成的文件,最少为两个!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                else
                {
                    string[] strFiles = txtCFile.Text.Split(',');
                    CombinFile(strFiles, txtCPath.Text, progressBar);
                }
            }
        }
        catch { }
    }

    //监视“分割”/“合并”按钮的可用状态
    private void timer_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.tabControl = new System.Windows.Forms.TabControl();
        this.tabPage = 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.label = new System.Windows.Forms.Label();
        this.cboxUnit = new System.Windows.Forms.ComboBox();
        this.label = 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.label = new System.Windows.Forms.Label();
        this.tabPage = new System.Windows.Forms.TabPage();
        this.txtCPath = new System.Windows.Forms.TextBox();
        this.txtCFile = new System.Windows.Forms.TextBox();
        this.label = 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.label = new System.Windows.Forms.Label();
        this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
        this.folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
        this.timer = new System.Windows.Forms.Timer(this.components);
        this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
        this.progressBar = new System.Windows.Forms.ProgressBar();
        this.tabControl.SuspendLayout();
        this.tabPage.SuspendLayout();
        this.tabPage.SuspendLayout();
        this.SuspendLayout();
        // 
        // tabControl
        // 
        this.tabControl.Controls.Add(this.tabPage1);
        this.tabControl.Controls.Add(this.tabPage2);
        this.tabControl.Dock = System.Windows.Forms.DockStyle.Fill;
        this.tabControl.Location = new System.Drawing.Point(0, 0);
        this.tabControl.Name = "tabControl1";
        this.tabControl.SelectedIndex = 0;
        this.tabControl.Size = new System.Drawing.Size(354, 201);
        this.tabControl.TabIndex = 0;
        // 
        // tabPage
        // 
        this.tabPage.Controls.Add(this.txtPath);
        this.tabPage.Controls.Add(this.txtLength);
        this.tabPage.Controls.Add(this.btnSPath);
        this.tabPage.Controls.Add(this.label3);
        this.tabPage.Controls.Add(this.cboxUnit);
        this.tabPage.Controls.Add(this.label2);
        this.tabPage.Controls.Add(this.btnSplit);
        this.tabPage.Controls.Add(this.btnSFile);
        this.tabPage.Controls.Add(this.txtFile);
        this.tabPage.Controls.Add(this.label1);
        this.tabPage.Location = new System.Drawing.Point(4, 21);
        this.tabPage.Name = "tabPage1";
        this.tabPage.Padding = new System.Windows.Forms.Padding(3);
        this.tabPage.Size = new System.Drawing.Size(346, 176);
        this.tabPage.TabIndex = 0;
        this.tabPage.Text = "文件分割";
        this.tabPage.UseVisualStyleBackColor = true;
        // 
        // txtPath
        // 
        this.txtPath.Location = new System.Drawing.Point(, 117);
        this.txtPath.Name = "txtPath";
        this.txtPath.Size = new System.Drawing.Size(, 21);
        this.txtPath.TabIndex =;
        // 
        // txtLength
        // 
        this.txtLength.Location = new System.Drawing.Point(, 72);
        this.txtLength.Name = "txtLength";
        this.txtLength.Size = new System.Drawing.Size(, 21);
        this.txtLength.TabIndex =;
        // 
        // btnSPath
        // 
        this.btnSPath.Location = new System.Drawing.Point(, 115);
        this.btnSPath.Name = "btnSPath";
        this.btnSPath.Size = new System.Drawing.Size(, 23);
        this.btnSPath.TabIndex =;
        this.btnSPath.Text = "<<";
        this.btnSPath.UseVisualStyleBackColor = true;
        this.btnSPath.Click += new System.EventHandler(this.btnSPath_Click);
        // 
        // label
        // 
        this.label.AutoSize = true;
        this.label.Location = new System.Drawing.Point(12, 100);
        this.label.Name = "label3";
        this.label.Size = new System.Drawing.Size(137, 12);
        this.label.TabIndex = 7;
        this.label.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(, 73);
        this.cboxUnit.Name = "cboxUnit";
        this.cboxUnit.Size = new System.Drawing.Size(, 20);
        this.cboxUnit.TabIndex =;
        // 
        // label
        // 
        this.label.AutoSize = true;
        this.label.Location = new System.Drawing.Point(12, 55);
        this.label.Name = "label2";
        this.label.Size = new System.Drawing.Size(101, 12);
        this.label.TabIndex = 5;
        this.label.Text = "设置分割文件大小";
        // 
        // btnSplit
        // 
        this.btnSplit.Location = new System.Drawing.Point(, 26);
        this.btnSplit.Name = "btnSplit";
        this.btnSplit.Size = new System.Drawing.Size(, 23);
        this.btnSplit.TabIndex =;
        this.btnSplit.Text = "分割";
        this.btnSplit.UseVisualStyleBackColor = true;
        this.btnSplit.Click += new System.EventHandler(this.btnSplit_Click);
        // 
        // btnSFile
        // 
        this.btnSFile.Location = new System.Drawing.Point(, 26);
        this.btnSFile.Name = "btnSFile";
        this.btnSFile.Size = new System.Drawing.Size(, 23);
        this.btnSFile.TabIndex =;
        this.btnSFile.Text = "<<";
        this.btnSFile.UseVisualStyleBackColor = true;
        this.btnSFile.Click += new System.EventHandler(this.btnSFile_Click);
        // 
        // txtFile
        // 
        this.txtFile.Location = new System.Drawing.Point(, 27);
        this.txtFile.Name = "txtFile";
        this.txtFile.Size = new System.Drawing.Size(, 21);
        this.txtFile.TabIndex =;
        // 
        // label
        // 
        this.label.AutoSize = true;
        this.label.Location = new System.Drawing.Point(12, 10);
        this.label.Name = "label1";
        this.label.Size = new System.Drawing.Size(113, 12);
        this.label.TabIndex = 0;
        this.label.Text = "请选择要分割的文件";
        // 
        // tabPage
        // 
        this.tabPage.Controls.Add(this.txtCPath);
        this.tabPage.Controls.Add(this.txtCFile);
        this.tabPage.Controls.Add(this.label5);
        this.tabPage.Controls.Add(this.btnCPath);
        this.tabPage.Controls.Add(this.btnCombin);
        this.tabPage.Controls.Add(this.btnCFile);
        this.tabPage.Controls.Add(this.label4);
        this.tabPage.Location = new System.Drawing.Point(4, 21);
        this.tabPage.Name = "tabPage2";
        this.tabPage.Padding = new System.Windows.Forms.Padding(3);
        this.tabPage.Size = new System.Drawing.Size(346, 176);
        this.tabPage.TabIndex = 1;
        this.tabPage.Text = "文件合成";
        this.tabPage.UseVisualStyleBackColor = true;
        // 
        // txtCPath
        // 
        this.txtCPath.Location = new System.Drawing.Point(, 88);
        this.txtCPath.Name = "txtCPath";
        this.txtCPath.Size = new System.Drawing.Size(, 21);
        this.txtCPath.TabIndex =;
        // 
        // txtCFile
        // 
        this.txtCFile.Location = new System.Drawing.Point(, 44);
        this.txtCFile.Name = "txtCFile";
        this.txtCFile.Size = new System.Drawing.Size(, 21);
        this.txtCFile.TabIndex =;
        // 
        // label
        // 
        this.label.AutoSize = true;
        this.label.Location = new System.Drawing.Point(11, 72);
        this.label.Name = "label5";
        this.label.Size = new System.Drawing.Size(173, 12);
        this.label.TabIndex = 4;
        this.label.Text = "选择合并后文件存放路径及名称";
        // 
        // btnCPath
        // 
        this.btnCPath.Location = new System.Drawing.Point(, 87);
        this.btnCPath.Name = "btnCPath";
        this.btnCPath.Size = new System.Drawing.Size(, 23);
        this.btnCPath.TabIndex =;
        this.btnCPath.Text = "<<";
        this.btnCPath.UseVisualStyleBackColor = true;
        this.btnCPath.Click += new System.EventHandler(this.btnCPath_Click);
        // 
        // btnCombin
        // 
        this.btnCombin.Location = new System.Drawing.Point(, 44);
        this.btnCombin.Name = "btnCombin";
        this.btnCombin.Size = new System.Drawing.Size(, 23);
        this.btnCombin.TabIndex =;
        this.btnCombin.Text = "合并";
        this.btnCombin.UseVisualStyleBackColor = true;
        this.btnCombin.Click += new System.EventHandler(this.btnCombin_Click);
        // 
        // btnCFile
        // 
        this.btnCFile.Location = new System.Drawing.Point(, 44);
        this.btnCFile.Name = "btnCFile";
        this.btnCFile.Size = new System.Drawing.Size(, 23);
        this.btnCFile.TabIndex =;
        this.btnCFile.Text = "<<";
        this.btnCFile.UseVisualStyleBackColor = true;
        this.btnCFile.Click += new System.EventHandler(this.btnCFile_Click);
        // 
        // label
        // 
        this.label.AutoSize = true;
        this.label.Location = new System.Drawing.Point(11, 28);
        this.label.Name = "label4";
        this.label.Size = new System.Drawing.Size(101, 12);
        this.label.TabIndex = 0;
        this.label.Text = "选择要合成的文件";
        // 
        // openFileDialog
        // 
        this.openFileDialog.Multiselect = true;
        // 
        // timer
        // 
        this.timer.Tick += new System.EventHandler(this.timer1_Tick);
        // 
        // progressBar
        // 
        this.progressBar.Dock = System.Windows.Forms.DockStyle.Bottom;
        this.progressBar.Location = new System.Drawing.Point(, 181);
        this.progressBar.Name = "progressBar";
        this.progressBar.Size = new System.Drawing.Size(, 20);
        this.progressBar.TabIndex =;
        // 
        // frmSplit
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(F, 12F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(, 201);
        this.Controls.Add(this.progressBar);
        this.Controls.Add(this.tabControl);
        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.tabControl.ResumeLayout(false);
        this.tabPage.ResumeLayout(false);
        this.tabPage.PerformLayout();
        this.tabPage.ResumeLayout(false);
        this.tabPage.PerformLayout();
        this.ResumeLayout(false);

    }

    #endregion

    public System.Windows.Forms.TabControl tabControl;
    private System.Windows.Forms.TabPage tabPage;
    private System.Windows.Forms.TextBox txtFile;
    private System.Windows.Forms.Label label;
    private System.Windows.Forms.TabPage tabPage;
    private System.Windows.Forms.TextBox txtPath;
    private System.Windows.Forms.TextBox txtLength;
    private System.Windows.Forms.Button btnSPath;
    private System.Windows.Forms.Label label;
    private System.Windows.Forms.ComboBox cboxUnit;
    private System.Windows.Forms.Label label;
    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 label;
    private System.Windows.Forms.Button btnCPath;
    private System.Windows.Forms.Button btnCombin;
    private System.Windows.Forms.Button btnCFile;
    private System.Windows.Forms.Label label;
    private System.Windows.Forms.Timer timer;
    private System.Windows.Forms.SaveFileDialog saveFileDialog;
    private System.Windows.Forms.ProgressBar progressBar;
}