c#檔案分割與合并 part 2

來源:互聯網
上載者:User

這是合并的部分,我們要讓在上一篇文章中被分割的檔案再合并起來,建立一個新的項目,相對於上一個項目,只是少了一個combox控制項,因為我們要合并檔案,所以不需要選擇檔案大小,設計圖如下:

同樣,引用system.IO,然後,給瀏覽按鈕添加如下代碼:

 

瀏覽
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Title = "請選擇要合并的第一個檔案";
System.Windows.Forms.DialogResult drTemp = openFileDialog1.ShowDialog();
if (drTemp == DialogResult.OK && openFileDialog1.FileName != "")
{
textBox1.Text = openFileDialog1.FileName;
}
string[] path = openFileDialog1.FileName.Split(@"\".ToCharArray());
string sTemp = "";
int i = 0;
for (i = 0; i < path.Length - 1; i++)
{
sTemp = sTemp + path[i] + @"\";
}
button1.Enabled = true;
sDirectoryName = sTemp;
//獲得檔案所在目錄

}

 

再給button2添加如下代碼:

 

合并
private void button2_Click(object sender, EventArgs e)
{
string[] arrFileNames = Directory.GetFiles(sDirectoryName);
//擷取存放分割後小檔案所在目錄所在的所有小檔案
int iSumFile = arrFileNames.Length;
progressBar1.Maximum = iSumFile;
FileStream AddStream = new FileStream(textBox2.Text, FileMode.OpenOrCreate);
//以合并後的檔案名稱和開啟檔案來建立、初始化FileStream檔案流
BinaryWriter AddWriter = new BinaryWriter(AddStream);
//以FileStream檔案流來初始化BinaryWriter書寫器,此用以合并分割的檔案
/*迴圈合并小檔案,並產生合并檔案 */
for (int i = 0; i < iSumFile; i++)
{
FileStream TempStream = new FileStream(arrFileNames[i], FileMode.Open);
//以小檔案所對應的檔案名稱和開啟模式來初始化FileStream檔案流,起讀取分割作用
BinaryReader TempReader = new BinaryReader(TempStream);
//用FileStream檔案流來初始化BinaryReader檔案閱讀器,也起讀取分割檔案作用
AddWriter.Write(TempReader.ReadBytes((int)TempStream.Length));
//讀取分割檔案中的資料,並產生合并後檔案
TempReader.Close();
//關閉BinaryReader檔案閱讀器
TempStream.Close();
//關閉FileStream檔案流
progressBar1.Value = i + 1;
//顯示合并進程
}
AddWriter.Close();
//關閉BinaryWriter檔案書寫器
AddStream.Close();
//關閉FileStream檔案流
MessageBox.Show("成功合并!");
progressBar1.Value = 0;
}

 

編譯後運行,我們找到剛才的檔案,選擇第一個0001.rar,然後進行合并,即可。

然後,可以在輸出檔案的目錄下,看到my.rar了。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.