如何等待文件可用

本文关键字:文件 等待 何等待 | 更新日期: 2023-09-27 18:26:57

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);
有时

它工作正常,有时我在此行上出现异常,说该文件正被另一个进程使用。

所以我想使用 IsFileLock 方法或其他方法来检查,直到文件未锁定。但是如果我在行之前调用此方法

LiveViewPicBox.Load(myFile.FullName);

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

如何等待文件可用

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。