【问题标题】:How do I wait for a file to become available? [duplicate]如何等待文件可用? [复制]
【发布时间】:2016-03-20 16:32:06
【问题描述】:
private void DisplayLastTakenPhoto()
{
    string mypath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures),"RemotePhoto");
    var directory = new DirectoryInfo(mypath);
    var myFile = directory.EnumerateFiles()
        .Where(f => f.Extension.Equals(".jpg", StringComparison.CurrentCultureIgnoreCase) || f.Extension.Equals("raw", StringComparison.CurrentCultureIgnoreCase))
        .OrderByDescending(f => f.LastWriteTime)
        .First();

    LiveViewPicBox.Load(myFile.FullName);
}

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

    try
    {
        stream = file.Open(FileMode.Open, FileAccess.Read, 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;
}

问题出在这行:

LiveViewPicBox.Load(myFile.FullName);

有时它工作正常有时我在这一行遇到异常,说该文件正在被另一个进程使用。

所以我想使用 IsFileLocked 方法或其他方法进行检查,直到文件未锁定。 但是如果我会在该行之前调用这个方法

LiveViewPicBox.Load(myFile.FullName);

它会检查文件是否只锁定了一次。我需要以某种方式使用 while 或其他方式来检查文件是否被一遍又一遍地锁定,直到它被解锁。 并且只有当它被解锁时才能使行 LiveViewPicBox.Load(myFile.FullName);

【问题讨论】:

  • 您可能喜欢阅读有关 MSDN: FileSystemWatcher 的内容,它会在目录或目录中的文件发生更改时侦听文件系统更改通知并引发事件。

标签: c# .net winforms


【解决方案1】:
public static bool IsFileReady(String sFilename)
{
    // If the file can be opened for exclusive access it means that the file
    // is no longer locked by another process.
    try
    {
        using (FileStream inputStream = File.Open(sFilename, FileMode.Open, FileAccess.Read, FileShare.None))
        {
            if (inputStream.Length > 0)
            {
                return true;
            }
            else
            {
                return false;
            }

        }
    }
    catch (Exception)
    {
        return false;
    }
}

将它放在一个循环中并等待它返回true。

【讨论】:

  • 这不是一个真正的答案。它可以返回 true 并在一毫秒后再次被锁定。
  • @cFrozenDeath 他专门要求一种方法来检查文件是否被持续解锁,他没有要求一种方法来锁定文件。
  • CopyPaste 答案不专业也不太好,无需添加任何内容。并且显然应该已将我评论的内容或您回答的地方标记为重复:stackoverflow.com/questions/50744/…
  • @CollinM.Stevens 是什么让您认为这里有一些一致性?我没有说“锁定文件”,我是说方法返回true后文件可能再次被阻塞。
  • @OrelEraki 我不能标记为重复,也不能评论答案,否则我会。我回答了他的问题,不多也不少。我不打算将他的问题标记为主持人干预,因为这是我可以标记的唯一选项。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-15
  • 1970-01-01
相关资源
最近更新 更多