判斷檔案是否鎖定中

例如正在寫入中,檔案還不完整

public static bool IsFileLocked(this System.IO.FileInfo file)
    {
        System.IO.FileStream stream = null;
        try
        {
            stream = file.Open(System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None);
        }
        catch 
        {
            //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;
    }

留言

熱門文章