C# 檔案複製

目的:實現檔案複製




private void button3_Click(object sender, EventArgs e)
{
    FileStream sourceFile = new FileStream(@"C:\Apache_OpenOffice_zh-TW.exe", FileMode.Open, FileAccess.Read);
    //sourceFile 來源檔要先在該路徑中準備好
            
    FileStream targetFile = new FileStream(@"C:\VS2012\CopyOpenOffice.exe", FileMode.Create, FileAccess.Write);
            
    int bb = -1;
    while ((bb = sourceFile.ReadByte()) != -1)
    {
        //一次1 byte的讀
        targetFile.WriteByte((byte)bb);
    }
    sourceFile.Close();
    targetFile.Close();
    MessageBox.Show("複製完畢!");
}
//-------------------------------------------------------------------------------------
private void button4_Click(object sender, EventArgs e)
{
    FileStream sourceFile = new FileStream(@"C:\Apache_OpenOffice_zh-TW.exe", FileMode.Open, FileAccess.Read);
    FileStream targetFile = new FileStream(@"C:\VS2012\CopyOpenOffice.exe", FileMode.Create, FileAccess.Write);

    int count = -1;
    byte[] bb = new byte[10240];
    while ((count = sourceFile.Read(bb,0,bb.Length))>0)
    {
        //一次讀10240個byte,相當於10k,效率較佳
        targetFile.Write(bb, 0, bb.Length);
    }
    sourceFile.Close();
    targetFile.Close();
    MessageBox.Show("複製完畢!");
}

留言

熱門文章