我想寫一個類,將文件從一個位置複製到另一個並報告進度。我遇到的問題是,當應用程序運行時,進度將立即從0到100%進行拍攝,但該文件仍在後臺進行復制。C#文件流不阻塞,直到寫入/讀取操作完成
public void Copy(string sourceFile, string destinationFile)
{
_stopWatch.Start();
_sourceStream = new FileStream(srcName, FileMode.Open);
_destinationStream = new FileStream(destName, FileMode.CreateNew);
read();
//On a 500mb file, execution will reach here in about a second.
}
private void read()
{
int i = _sourceStream.Read(_buffer, 0, bufferSize);
_completedBytes += i;
if (i != 0)
{
_destinationStream.Write(_buffer, 0, i);
TriggerProgressUpdate();
read();
}
}
private void TriggerProgressUpdate()
{
if (OnCopyProgress != null)
{
CopyProgressEventArgs arg = new CopyProgressEventArgs();
arg.CompleteBytes = _completedBytes;
if (_totalBytes == 0)
_totalBytes = new FileInfo(srcName).Length;
arg.TotalBytes = _totalBytes;
OnCopyProgress(this, arg);
}
}
什麼似乎是發生的是的FileStream只是排隊的操作的操作系統,而不是阻止,直到讀或寫操作完成。
有什麼辦法可以禁用此功能而不會導致巨大的性能損失?
PS。我正在使用測試源和目標變量,這就是爲什麼他們不符合參數。
感謝 克雷格
作爲一個利益的問題,是否有一個原因,你迫使你的應用程序複製一個文件到另一個字節,而不是調用File.Copy()? – 2011-02-11 07:49:10
@bitcrazed:可能會得到一個進度指示器。 – Guffa 2011-02-11 07:53:47