我如何等待文件可用?

时间:2015-12-15 01:57:11

标签: c# .net winforms

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或somet其他方式来检查文件是否一次又一次地被锁定,直到它被解锁。 并且只有当它解锁才能生成LiveViewPicBox.Load(myFile.FullName);

1 个答案:

答案 0 :(得分:-2)

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。