C 實現檔案複製 更新 實時顯示進度條

2021-04-23 08:07:20 字數 2482 閱讀 4237

在複製更新檔案時,如果想要實時的獲得檔案複製的進度,並顯示在窗體的進度條上有許多方法,在尋找了一段資料後,我整理了一些別人的**,獲得到本篇的**,**實現了根據配置檔案,複製檔案列表的效果.思路其實很簡單,就是非同步的讀取和寫入流,在非同步**的方法中,響應窗體的進度條控制項,所有注釋都寫在**中了.

相關**:http://download.csdn.net/source/880686

程式介面:

int totalsize;                 //讀取檔案總大小

int position;                  //當前讀取位置

int buffer_size = 1024;        //快取大小

xmldocument xmldoc;            //配置xml檔案上下文

private

class _copy

list<_copy> copylist;       //複製列表

public form1()

private

void form1_load(object sender, eventargs e)

else

//目標檔案位址

copylist.add(copy);

}//如果更新列表沒有值,則退出,執行程式

if (copylist.count <= 0)

totalsize = 0;

for (int i = 0; i < copylist.count; i++)

filestream fs = new filestream(copylist[i].srcfile, filemode.open, fileaccess.read);

totalsize += (int)fs.length;

copylist[i].size = (int)fs.length;

copylist[i].stream = fs;

//這裡是設定快取的大小,可以根據需要修改邏輯

buffer_size = copylist[i].size / 50;

if (buffer_size < 10 * 1024)

//快取的大小要設定的比總大小要小,否則無法讀取

if (totalsize > buffer_size)

else

}catch (exception ex)}}

private

void asynccopyfile(iasyncresult ar)

//寫入檔案

fswriter.write(copy.buffer, 0, copy.buffer.length);

fswriter.close();

//當前檔案流位置

lock (copy.stream)

//響應進度條

methodinvoker m = new methodinvoker(synchprogressbar);

m.begininvoke(null, null);

//讀取完畢

if (copy.position >= copy.size)

//繼續讀取下個快取

lock (copy.stream)

}catch (exception ex)

}public

delegate

void delegate_synprogress();

private

void synchprogressbar()

else

this.progressbar1.maximum = totalsize;

this.progressbar1.value = position;}}

配置檔案說明

程式的配置檔案為config.xml,格式如下:

<

config

>

<

update

>

<

path

>c:/

path

>

<

name

>1.exe

name

>

update

>

<

update

>

<

path

>d:/

path

>

<

name

>2.rar

name

>

update

>

config

>

填寫複製的源路徑是原始檔的檔名,節點可以有多個.

小結程式在複製失敗上做了乙個備份恢復的功能,沒有進行詳細的測試,在非同步程式中,異常的捕獲要在程式塊的最裡層(這個和執行緒很相似,否則程式會因為捕獲不到異常而出現程式崩潰的情況,就執行不到檔案恢復了.),所以我在非同步呼叫的**方法中些了檔案恢復的功能.程式還有很多功能沒有考慮,比如,目標檔名不能更改,路徑也不能更改等.

C 複製檔案時候顯示進度

using system using system.collections.generic using system.componentmodel using system.data using system.drawing using system.linq using system.text u...

使用C 在進度條中顯示複製檔案的進度

public class frmmain system.windows.forms.form 清理所有正在使用的資源。protected override void dispose bool disposing base.dispose disposing region initialize com...

使用C 在進度條中顯示複製檔案的進度

region using directives using system using system.io using system.xml using system.collections using system.reflection using system.text using system....