大檔案Copy

iSQlServer發表於2010-08-24
private void button3_Click(object sender, EventArgs e)
        {
           
            Thread thread = null;
            //為了不讓介面死掉,要將該操作放在一個執行緒中
            thread = new Thread
                (
                () =>
                {
                    //告訴系統不去檢測非法的跨執行緒呼叫
                    CheckForIllegalCrossThreadCalls = false;
                   
                    //建立一個檔案流指向原始檔
                    FileStream fsRead = new FileStream(this.textBox1.Text, FileMode.Open);
                    //建立一個檔案流指向目標檔案
                    FileStream fsWrite = new FileStream(this.textBox2.Text, FileMode.Create);
                    //記錄一下該檔案的長度
                    long fileLength = fsRead.Length;
                    //定義一個1M的緩衝區
                    byte[] buffer = new byte[1024 * 1024];
                    //先讀取一次,並且將讀取到的真正內容長度記錄下來
                    int readLength = fsRead.Read(buffer, 0, buffer.Length);
                    //用來記錄已經將多少內容寫入到了檔案中
                    long readCount = 0;
                    //只要讀取到的內容不為0就接著讀
                    while (readLength!=0)
                    {
                        //將前面已經讀取到記憶體中的資料寫入到檔案中
                        fsWrite.Write(buffer ,0,readLength);
                        //已經讀取的數量累加
                        readCount += readLength;
                        //計算已經讀取的資料百分比
                        int percentage =(int)( readCount * 100 / fileLength);
                        this.progressBar1.Value = percentage;
                        //進行下一次讀取
                        readLength = fsRead.Read(buffer, 0, buffer.Length);

                    }
                    fsRead.Close();
                    fsWrite.Close();
                    //清空緩衝區
                    buffer = null;
                    //回收一下記憶體
                    GC.Collect();
                    thread.Abort();
                   
                }
                );
            thread.Start();
        }

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/16436858/viewspace-671712/,如需轉載,請註明出處,否則將追究法律責任。

相關文章