c# - System.IO.File.Move--如何等待移动完成?

标签 c# wpf

我正在用 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/

相关文章:

c# - 如何在 WPF 应用程序中使用 windows 键

c# - Xamarin Android 绑定(bind)库 - 不在 DigitalPersona UareU JAR 中实现继承的抽象成员

c# - 静态构造函数和实例构造函数的调用

c# - 带TimeSpan的定时器和自制定时器比秒表慢

WPF 路由命令和 ShowDialog 窗口

c# - RichTextBox C# 以编程方式触发某些函数

c# - 具有列的 Wpf TreeView,具有 UI 虚拟化和 DataVirtualization

c# - 如何在C#中一次性执行两个查询?

c# - System.Web.HttpUtility.HtmlDecode 不适用于测试 %3cstrong%3ebold %3c/strong%3etest

c# - WebAPI 和 ILMerge(又名自托管单个 exe)