我在c#中编写一个WPF应用程序,我需要移动一些文件 - 我真的需要知道文件是否成功.为此,我编写了一个检查,确保文件在移动后到达目标目录 - 问题是有时我会在文件完成移动之前进行检查:
System.IO.File.Move(file.FullName, endLocationWithFile);
System.IO.FileInfo[] filesInDirectory = endLocation.GetFiles();
foreach (System.IO.FileInfo temp in filesInDirectory)
{
if (temp.Name == shortFileName)
{
return true;
}
}
// The file we sent over has not gotten to the correct directory....something went wrong!
throw new IOException("File did not reach destination");
}
catch (Exception e)
{
//Something went wrong, return a fail;
logger.writeErrorLog(e);
return false;
}
Run Code Online (Sandbox Code Playgroud)
有人可以告诉我如何确保文件实际到达目的地吗? - 我将要移动的文件可能非常大 - (全高清mp4文件长达2小时)
谢谢!
您可以使用流Aysnc
Await
来确保文件完全复制
这样的事情应该有效:
private void Button_Click(object sender, RoutedEventArgs e)
{
string sourceFile = @"\\HOMESERVER\Development Backup\Software\Microsoft\en_expression_studio_4_premium_x86_dvd_537029.iso";
string destinationFile = "G:\\en_expression_studio_4_premium_x86_dvd_537029.iso";
MoveFile(sourceFile, destinationFile);
}
private async void MoveFile(string sourceFile, string destinationFile)
{
try
{
using (FileStream sourceStream = File.Open(sourceFile, FileMode.Open))
{
using (FileStream destinationStream = File.Create(destinationFile))
{
await sourceStream.CopyToAsync(destinationStream);
if (MessageBox.Show("I made it in one piece :), would you like to delete me from the original file?", "Done", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
{
sourceStream.Close();
File.Delete(sourceFile);
}
}
}
}
catch (IOException ioex)
{
MessageBox.Show("An IOException occured during move, " + ioex.Message);
}
catch (Exception ex)
{
MessageBox.Show("An Exception occured during move, " + ex.Message);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您使用的是VS2010,则必须安装Async CTP才能使用新的Async/Await语法
归档时间: |
|
查看次数: |
11486 次 |
最近记录: |