我正在用 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;
}
有人能告诉我如何确保文件真正到达目的地吗?--我要移动的文件可能非常大--(长达 2 小时的全高清 mp4 文件)
谢谢!
最佳答案
您可以将流与 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);
}
}
如果您使用 VS2010,则必须安装 Async CTP使用新的 Async/Await 语法
关于c# - System.IO.File.Move--如何等待移动完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14162983/