等到文件完全写入

时间:2012-06-11 14:29:58

标签: c# file io filesystems copy

在一个目录中创建文件(FileSystemWatcher_Created)时,我将其复制到另一个目录中。但是当我创建一个大的(> 10MB)文件时,它无法复制文件,因为它已经开始复制,当文件尚未完成创建时...
这会导致无法复制文件,因为它会被另一个进程用于引发。 ;(
有什么帮助吗?

class Program
{
    static void Main(string[] args)
    {
        string path = @"D:\levan\FolderListenerTest\ListenedFolder";
        FileSystemWatcher listener; 
        listener = new FileSystemWatcher(path);
        listener.Created += new FileSystemEventHandler(listener_Created);
        listener.EnableRaisingEvents = true;

        while (Console.ReadLine() != "exit") ;
    }

    public static void listener_Created(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine
                (
                    "File Created:\n"
                   + "ChangeType: " + e.ChangeType
                   + "\nName: " + e.Name
                   + "\nFullPath: " + e.FullPath
                );
        File.Copy(e.FullPath, @"D:\levan\FolderListenerTest\CopiedFilesFolder\" + e.Name);
        Console.Read();
    }
}

9 个答案:

答案 0 :(得分:39)

您遇到的问题只有解决方法。

在开始复制过程之前检查文件ID是否正在进行中。您可以调用以下函数,直到获得False值。

第一种方法,直接从this answer复制:

private bool IsFileLocked(FileInfo file)
{
    FileStream stream = null;

    try
    {
        stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    }
    catch (IOException)
    {
        //the file is unavailable because it is:
        //still being written to
        //or being processed by another thread
        //or does not exist (has already been processed)
        return true;
    }
    finally
    {
        if (stream != null)
            stream.Close();
    }

    //file is not locked
    return false;
}

第二种方法:

const int ERROR_SHARING_VIOLATION = 32;
const int ERROR_LOCK_VIOLATION = 33;
private bool IsFileLocked(string file)
{
    //check that problem is not in destination file
    if (File.Exists(file) == true)
    {
        FileStream stream = null;
        try
        {
            stream = File.Open(file, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
        }
        catch (Exception ex2)
        {
            //_log.WriteLog(ex2, "Error in checking whether file is locked " + file);
            int errorCode = Marshal.GetHRForException(ex2) & ((1 << 16) - 1);
            if ((ex2 is IOException) && (errorCode == ERROR_SHARING_VIOLATION || errorCode == ERROR_LOCK_VIOLATION))
            {
                return true;
            }
        }
        finally
        {
            if (stream != null)
                stream.Close();
        }
    }
    return false;
}

答案 1 :(得分:10)

这是一个旧帖子,但我会为其他人添加一些信息。

我在编写PDF文件的程序时遇到了类似的问题,有时它们需要30秒才能渲染..这与我的watcher_FileCreated类在复制文件之前等待的时间相同。

文件未被锁定。

在这种情况下,我检查了PDF的大小,然后在比较新大小之前等待了2秒,如果它们不相等,则线程将睡眠30秒并重试。

答案 2 :(得分:9)

来自FileSystemWatcher的文档:

  

创建文件后立即引发OnCreated事件。如果是文件   被复制或转移到监视目录,   OnCreated事件将立即引发,然后是一个或多个事件   OnChanged事件。

因此,如果复制失败,(捕获异常),将其添加到仍需要移动的文件列表中,并在OnChanged事件期间尝试复制。最终,它应该工作。

像(不完整;捕获特定异常,初始化变量等):

    public static void listener_Created(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine
                (
                    "File Created:\n"
                   + "ChangeType: " + e.ChangeType
                   + "\nName: " + e.Name
                   + "\nFullPath: " + e.FullPath
                );
        try {
            File.Copy(e.FullPath, @"D:\levani\FolderListenerTest\CopiedFilesFolder\" + e.Name);
        }
        catch {
            _waitingForClose.Add(e.FullPath);
        }
        Console.Read();
    }

    public static void listener_Changed(object sender, FileSystemEventArgs e)
    {
         if (_waitingForClose.Contains(e.FullPath))
         {
              try {
                  File.Copy(...);
                  _waitingForClose.Remove(e.FullPath);
              }
              catch {}
         }
   }

答案 3 :(得分:5)

你真的很幸运 - 编写文件的程序将其锁定,因此您无法打开它。如果它没有锁定它,你就会复制一个部分文件,而不知道是否有问题。

当你无法访问文件时,你可以假设它仍在使用中(更好的是 - 尝试以独占模式打开它,看看是否有其他人正在打开它,而不是猜测File的失败。复制)。如果文件被锁定,您将不得不在其他时间复制它。如果它没有锁定,你可以复制它(这里有一个竞争条件的可能性很小)。

那个'其他时间'是什么时候?我不记得FileSystemWatcher每个文件发送多个事件 - 检查出来,它可能足以让你简单地忽略该事件并等待另一个事件。如果没有,您可以随时设置时间并在5秒内重新检查文件。

答案 4 :(得分:2)

你已经自己给出了答案;你必须等待文件的创建才能完成。一种方法是通过检查文件是否仍在使用。可在此处找到此示例:Is there a way to check if a file is in use?

请注意,您必须修改此代码才能使其适用于您的情况。你可能想要(伪代码):

public static void listener_Created()
{
   while CheckFileInUse()
      wait 1000 milliseconds

   CopyFile()
}

显然,如果所有者应用程序永远不会释放锁,您应该保护自己免受无限while的攻击。此外,可能值得查看您可以订阅的FileSystemWatcher中的其他事件。可能有一个事件可以用来规避整个问题。

答案 5 :(得分:2)

所以,快速浏览了其中一些和其他类似的问题,我今天下午进行了一次快乐的追逐尝试使用文件作为同步(以及文件保存)方法解决两个独立程序的问题。有点不寻常的情况,但它肯定突出了'检查文件是否被锁定的问题,然后打开它,如果它不是'接近。

问题是:文件可以在您检查文件的时间与实际打开文件的时间之间变为。很难追踪零星的无法复制文件,因为如果你不是在寻找它,它会被另一个进程错误使用。

基本的解决方案是尝试在catch块中打开文件,这样如果它被锁定,你可以再试一次。这样,在检查和打开之间没有经过的时间,操作系统同时执行它们。

此处的代码使用File.Copy,但它与File类的任何静态方法一样有效:File.Open,File.ReadAllText,File.WriteAllText等。

/// <param name="timeout">how long to keep trying in milliseconds</param>
static void safeCopy(string src, string dst, int timeout)
{
    while (timeout > 0)
    {
        try
        {
            File.Copy(src, dst);

            //don't forget to either return from the function or break out fo the while loop
            break;
        }
        catch (IOException)
        {
            //you could do the sleep in here, but its probably a good idea to exit the error handler as soon as possible
        }
        Thread.Sleep(100);

        //if its a very long wait this will acumulate very small errors. 
        //For most things it's probably fine, but if you need precision over a long time span, consider
        //   using some sort of timer or DateTime.Now as a better alternative
        timeout -= 100;
    }
}

关于Parellelism的另一个小记录: 这是一个同步方法,它将在等待和处理线程时阻塞其线程。这是最简单的方法,但如果文件长时间保持锁定状态,您的程序可能会无响应。在这里,Parellelism是一个太深入的主题,(并且你可以设置异步读/写的方式有点荒谬)但是这里有一种方法可以解决这个问题。

public class FileEx
{
    public static async void CopyWaitAsync(string src, string dst, int timeout, Action doWhenDone)
    {
        while (timeout > 0)
        {
            try
            {
                File.Copy(src, dst);
                doWhenDone();
                break;
            }
            catch (IOException) { }

            await Task.Delay(100);
            timeout -= 100;
        }
    }

    public static async Task<string> ReadAllTextWaitAsync(string filePath, int timeout)
    {
        while (timeout > 0)
        {
            try {
                return File.ReadAllText(filePath);
            }
            catch (IOException) { }

            await Task.Delay(100);
            timeout -= 100;
        }
        return "";
    }

    public static async void WriteAllTextWaitAsync(string filePath, string contents, int timeout)
    {
        while (timeout > 0)
        {
            try
            {
                File.WriteAllText(filePath, contents);
                return;
            }
            catch (IOException) { }

            await Task.Delay(100);
            timeout -= 100;
        }
    }
}

以下是它的使用方法:

public static void Main()
{
    test_FileEx();
    Console.WriteLine("Me First!");
}    

public static async void test_FileEx()
{
    await Task.Delay(1);

    //you can do this, but it gives a compiler warning because it can potentially return immediately without finishing the copy
    //As a side note, if the file is not locked this will not return until the copy operation completes. Async functions run synchronously
    //until the first 'await'. See the documentation for async: https://msdn.microsoft.com/en-us/library/hh156513.aspx
    CopyWaitAsync("file1.txt", "file1.bat", 1000);

    //this is the normal way of using this kind of async function. Execution of the following lines will always occur AFTER the copy finishes
    await CopyWaitAsync("file1.txt", "file1.readme", 1000);
    Console.WriteLine("file1.txt copied to file1.readme");

    //The following line doesn't cause a compiler error, but it doesn't make any sense either.
    ReadAllTextWaitAsync("file1.readme", 1000);

    //To get the return value of the function, you have to use this function with the await keyword
    string text = await ReadAllTextWaitAsync("file1.readme", 1000);
    Console.WriteLine("file1.readme says: " + text);
}

//Output:
//Me First!
//file1.txt copied to file1.readme
//file1.readme says: Text to be duplicated!

答案 6 :(得分:1)

当文件以二进制(逐字节)写入时,创建FileStream及以上解决方案不起作用,因为文件已准备好并且在每个字节中编写,因此在这种情况下,您需要其他解决方法,如下所示: 在创建文件或要在文件

上开始处理时执行此操作
long fileSize = 0;
currentFile = new FileInfo(path);

while (fileSize < currentFile.Length)//check size is stable or increased
{
  fileSize = currentFile.Length;//get current size
  System.Threading.Thread.Sleep(500);//wait a moment for processing copy
  currentFile.Refresh();//refresh length value
}

//Now file is ready for any process!

答案 7 :(得分:0)

您可以使用以下代码检查是否可以使用独占访问权打开文件(即,它不会被其他应用程序打开)。如果文件未关闭,您可以稍等片刻再次检查,直到文件关闭,您可以安全地复制它。

您仍然应该检查File.Copy是否失败,因为另一个应用程序可能会在您检查文件和复制文件之间打开文件。

public static bool IsFileClosed(string filename)
{
    try
    {
        using (var inputStream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None))
        {
            return true;
        }
    }
    catch (IOException)
    {
        return false;
    }
}

答案 8 :(得分:-5)

我想在这里添加一个答案,因为这对我有用。我使用时间延迟,循环,我能想到的一切。

我打开了输出文件夹的Windows资源管理器窗口。我把它关上了,一切都像魅力一样。

我希望这有助于某人。