使用File.Copy复制时“正在使用文件”异常

时间:2014-08-10 15:22:13

标签: c# .net io

当USB存储设备插入计算机时,我正在将文件从一个地方复制到另一个地方,而我的代码基于this MSDN example。但是,每当我运行它并插入闪存驱动器(/记忆棒/笔式驱动器等)时,代码就会运行,并引发以下异常:

System.IO.IOException: The process cannot access the file 'H:\Test document.txt' because it is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCore, String maybeFullPath)
at System.IO.File.InternalCopy(String sourceFileName, String destFileName, Boolean overwrite, Boolean checkHost)
at System.IO.File.Copy(String sourceFileName, String destFileName, Boolean overwrite)
at the location in my source.

H:\Test document.txt是源文件。

这是我的来源:

private int sync(string source, string target)
{
    MessageBox.Show("Running - "+source+"->"+target);

    //TODO: Iterate through directory tree
    if (!Directory.Exists(source))
    {
        MessageBox.Show("Failed");
        return 1; //Source doesn't exist
    }
    if (!Directory.Exists(target))
    {
        MessageBox.Show("Creating target");
        Directory.CreateDirectory(target);
    }

    try
    {
        string[] files = Directory.GetFiles(source);
        foreach (string str in files)
        {
            string fileName = Path.GetFileName(str);
            string fileDestPath = Path.Combine(target, str);
            File.Copy(str, fileDestPath, true); //This is the line where the exception is being thrown
        }
    }
    catch (Exception e)
    {
        MessageBox.Show("exception thrown - " + e); //above exception is being caught here
    }

    MessageBox.Show("Copied");

    return 0;
}

为什么在尝试阅读文件时抛出异常(我在网上看到的所有问题都与编写文件有关,这是有意义的),有什么我可以做的停止它

1 个答案:

答案 0 :(得分:3)

这很可能是一个错误。

Path.Combine(target, str);

可能应该是:

Path.Combine(target, fileName);