Frage

Auf diese Frage gibt es hier bereits eine Antwort:

Gibt es eine Möglichkeit zu überprüfen, ob eine Datei gesperrt ist, ohne einen Try/Catch-Block zu verwenden?

Im Moment ist die einzige Möglichkeit, die ich kenne, einfach die Datei zu öffnen und sie abzufangen System.IO.IOException.

War es hilfreich?

Lösung

Leider nein, und wenn Sie darüber nachdenken, wären diese Informationen sowieso wertlos, da die Datei in der nächsten Sekunde gesperrt werden könnte (lesen Sie:kurze Zeitspanne).

Warum genau müssen Sie wissen, ob die Datei überhaupt gesperrt ist?Wenn wir das wissen, können wir Ihnen vielleicht auf andere Weise gute Ratschläge geben.

Wenn Ihr Code so aussehen würde:

if not locked then
    open and update file

Dann könnte zwischen den beiden Zeilen ein anderer Prozess die Datei leicht sperren, was zu demselben Problem führen würde, das Sie zunächst vermeiden wollten:Ausnahmen.

Andere Tipps

Als ich mit einem ähnlichen Problem konfrontiert war, habe ich es mit dem folgenden Code abgeschlossen:

public bool IsFileLocked(string filePath)
{
    try
    {
        using (File.Open(filePath, FileMode.Open)){}
    }
    catch (IOException e)
    {
        var errorCode = Marshal.GetHRForException(e) & ((1 << 16) - 1);

        return errorCode == 32 || errorCode == 33;
    }

    return false;
}

Die anderen Antworten basieren auf alten Informationen.Dieser bietet eine bessere Lösung.

Vor langer Zeit war es unmöglich, die Liste der Prozesse, die eine Datei sperrten, zuverlässig abzurufen, weil Windows diese Informationen einfach nicht nachverfolgte.Zur Unterstützung der Starten Sie die Manager-API neu, diese Informationen werden jetzt verfolgt.Die Restart Manager-API ist ab Windows Vista und Windows Server 2008 verfügbar (Neustart-Manager:Laufzeitanforderungen).

Ich habe Code zusammengestellt, der den Pfad einer Datei annimmt und a zurückgibt List<Process> aller Prozesse, die diese Datei sperren.

static public class FileUtil
{
    [StructLayout(LayoutKind.Sequential)]
    struct RM_UNIQUE_PROCESS
    {
        public int dwProcessId;
        public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime;
    }

    const int RmRebootReasonNone = 0;
    const int CCH_RM_MAX_APP_NAME = 255;
    const int CCH_RM_MAX_SVC_NAME = 63;

    enum RM_APP_TYPE
    {
        RmUnknownApp = 0,
        RmMainWindow = 1,
        RmOtherWindow = 2,
        RmService = 3,
        RmExplorer = 4,
        RmConsole = 5,
        RmCritical = 1000
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    struct RM_PROCESS_INFO
    {
        public RM_UNIQUE_PROCESS Process;

        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_APP_NAME + 1)]
        public string strAppName;

        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_SVC_NAME + 1)]
        public string strServiceShortName;

        public RM_APP_TYPE ApplicationType;
        public uint AppStatus;
        public uint TSSessionId;
        [MarshalAs(UnmanagedType.Bool)]
        public bool bRestartable;
    }

    [DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)]
    static extern int RmRegisterResources(uint pSessionHandle,
                                          UInt32 nFiles,
                                          string[] rgsFilenames,
                                          UInt32 nApplications,
                                          [In] RM_UNIQUE_PROCESS[] rgApplications,
                                          UInt32 nServices,
                                          string[] rgsServiceNames);

    [DllImport("rstrtmgr.dll", CharSet = CharSet.Auto)]
    static extern int RmStartSession(out uint pSessionHandle, int dwSessionFlags, string strSessionKey);

    [DllImport("rstrtmgr.dll")]
    static extern int RmEndSession(uint pSessionHandle);

    [DllImport("rstrtmgr.dll")]
    static extern int RmGetList(uint dwSessionHandle,
                                out uint pnProcInfoNeeded,
                                ref uint pnProcInfo,
                                [In, Out] RM_PROCESS_INFO[] rgAffectedApps,
                                ref uint lpdwRebootReasons);

    /// <summary>
    /// Find out what process(es) have a lock on the specified file.
    /// </summary>
    /// <param name="path">Path of the file.</param>
    /// <returns>Processes locking the file</returns>
    /// <remarks>See also:
    /// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373661(v=vs.85).aspx
    /// http://wyupdate.googlecode.com/svn-history/r401/trunk/frmFilesInUse.cs (no copyright in code at time of viewing)
    /// 
    /// </remarks>
    static public List<Process> WhoIsLocking(string path)
    {
        uint handle;
        string key = Guid.NewGuid().ToString();
        List<Process> processes = new List<Process>();

        int res = RmStartSession(out handle, 0, key);

        if (res != 0)
            throw new Exception("Could not begin restart session.  Unable to determine file locker.");

        try
        {
            const int ERROR_MORE_DATA = 234;
            uint pnProcInfoNeeded = 0,
                 pnProcInfo = 0,
                 lpdwRebootReasons = RmRebootReasonNone;

            string[] resources = new string[] { path }; // Just checking on one resource.

            res = RmRegisterResources(handle, (uint)resources.Length, resources, 0, null, 0, null);

            if (res != 0) 
                throw new Exception("Could not register resource.");                                    

            //Note: there's a race condition here -- the first call to RmGetList() returns
            //      the total number of process. However, when we call RmGetList() again to get
            //      the actual processes this number may have increased.
            res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, null, ref lpdwRebootReasons);

            if (res == ERROR_MORE_DATA)
            {
                // Create an array to store the process results
                RM_PROCESS_INFO[] processInfo = new RM_PROCESS_INFO[pnProcInfoNeeded];
                pnProcInfo = pnProcInfoNeeded;

                // Get the list
                res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons);

                if (res == 0)
                {
                    processes = new List<Process>((int)pnProcInfo);

                    // Enumerate all of the results and add them to the 
                    // list to be returned
                    for (int i = 0; i < pnProcInfo; i++)
                    {
                        try
                        {
                            processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId));
                        }
                        // catch the error -- in case the process is no longer running
                        catch (ArgumentException) { }
                    }
                }
                else
                    throw new Exception("Could not list processes locking resource.");                    
            }
            else if (res != 0)
                throw new Exception("Could not list processes locking resource. Failed to get size of result.");                    
        }
        finally
        {
            RmEndSession(handle);
        }

        return processes;
    }
}

AKTUALISIEREN

Hier ist noch einer Diskussion mit Beispielcode Informationen zur Verwendung der Restart Manager-API.

Sie können auch überprüfen, ob ein Prozess diese Datei verwendet, und eine Liste der Programme anzeigen, die Sie schließen müssen, um fortzufahren, wie es ein Installationsprogramm tut.

public static string GetFileProcessName(string filePath)
{
    Process[] procs = Process.GetProcesses();
    string fileName = Path.GetFileName(filePath);

    foreach (Process proc in procs)
    {
        if (proc.MainWindowHandle != new IntPtr(0) && !proc.HasExited)
        {
            ProcessModule[] arr = new ProcessModule[proc.Modules.Count];

            foreach (ProcessModule pm in proc.Modules)
            {
                if (pm.ModuleName == fileName)
                    return proc.ProcessName;
            }
        }
    }

    return null;
}

Anstatt Interop zu verwenden, können Sie die .NET FileStream-Klassenmethoden Lock und Unlock verwenden:

FileStream.Lockhttp://msdn.microsoft.com/en-us/library/system.io.filestream.lock.aspx

FileStream.Unlockhttp://msdn.microsoft.com/en-us/library/system.io.filestream.unlock.aspx

Du könntest anrufen Sperrdatei über Interop für den Dateibereich, an dem Sie interessiert sind.Dadurch wird keine Ausnahme ausgelöst. Wenn dies gelingt, wird der Teil der Datei (der von Ihrem Prozess gehalten wird) gesperrt. Diese Sperre bleibt bestehen, bis Sie aufrufen UnlockFile oder Ihr Prozess stirbt.

Eine Variation der hervorragenden Antwort von DixonD (oben).

public static bool TryOpen(string path,
                           FileMode fileMode,
                           FileAccess fileAccess,
                           FileShare fileShare,
                           TimeSpan timeout,
                           out Stream stream)
{
    var endTime = DateTime.Now + timeout;

    while (DateTime.Now < endTime)
    {
        if (TryOpen(path, fileMode, fileAccess, fileShare, out stream))
            return true;
    }

    stream = null;
    return false;
}

public static bool TryOpen(string path,
                           FileMode fileMode,
                           FileAccess fileAccess,
                           FileShare fileShare,
                           out Stream stream)
{
    try
    {
        stream = File.Open(path, fileMode, fileAccess, fileShare);
        return true;
    }
    catch (IOException e)
    {
        if (!FileIsLocked(e))
            throw;

        stream = null;
        return false;
    }
}

private const uint HRFileLocked = 0x80070020;
private const uint HRPortionOfFileLocked = 0x80070021;

private static bool FileIsLocked(IOException ioException)
{
    var errorCode = (uint)Marshal.GetHRForException(ioException);
    return errorCode == HRFileLocked || errorCode == HRPortionOfFileLocked;
}

Verwendung:

private void Sample(string filePath)
{
    Stream stream = null;

    try
    {
        var timeOut = TimeSpan.FromSeconds(1);

        if (!TryOpen(filePath,
                     FileMode.Open,
                     FileAccess.ReadWrite,
                     FileShare.ReadWrite,
                     timeOut,
                     out stream))
            return;

        // Use stream...
    }
    finally
    {
        if (stream != null)
            stream.Close();
    }
}

Hier ist eine Variation des DixonD-Codes, die die Wartezeit auf das Entsperren der Datei in Sekunden hinzufügt und es erneut versucht:

public bool IsFileLocked(string filePath, int secondsToWait)
{
    bool isLocked = true;
    int i = 0;

    while (isLocked &&  ((i < secondsToWait) || (secondsToWait == 0)))
    {
        try
        {
            using (File.Open(filePath, FileMode.Open)) { }
            return false;
        }
        catch (IOException e)
        {
            var errorCode = Marshal.GetHRForException(e) & ((1 << 16) - 1);
            isLocked = errorCode == 32 || errorCode == 33;
            i++;

            if (secondsToWait !=0)
                new System.Threading.ManualResetEvent(false).WaitOne(1000);
        }
    }

    return isLocked;
}


if (!IsFileLocked(file, 10))
{
    ...
}
else
{
    throw new Exception(...);
}

Dann könnte zwischen den beiden Zeilen ein anderer Prozess die Datei leicht sperren, was zu demselben Problem führen würde, das Sie zunächst vermeiden wollten:Ausnahmen.

Auf diese Weise wissen Sie jedoch, dass das Problem vorübergehend ist, und können es später erneut versuchen.(Sie könnten beispielsweise einen Thread schreiben, der, wenn er beim Schreibversuch auf eine Sperre stößt, es so lange erneut versucht, bis die Sperre aufgehoben wird.)

Andererseits ist die IOException für sich genommen nicht spezifisch genug, dass das Sperren die Ursache für den E/A-Fehler wäre.Es kann Gründe geben, die nicht vorübergehender Natur sind.

Sie können feststellen, ob die Datei gesperrt ist, indem Sie zunächst versuchen, sie selbst zu lesen oder zu sperren.

Weitere Informationen finden Sie in meiner Antwort hier.

Das Gleiche, aber in Powershell

function Test-FileOpen
{
    Param
    ([string]$FileToOpen)
    try
    {
        $openFile =([system.io.file]::Open($FileToOpen,[system.io.filemode]::Open))
        $open =$true
        $openFile.close()
    }
    catch
    {
        $open = $false
    }
    $open
}

Am Ende habe ich Folgendes getan:

internal void LoadExternalData() {
    FileStream file;

    if (TryOpenRead("filepath/filename", 5, out file)) {
        using (file)
        using (StreamReader reader = new StreamReader(file)) {
         // do something 
        }
    }
}


internal bool TryOpenRead(string path, int timeout, out FileStream file) {
    bool isLocked = true;
    bool condition = true;

    do {
        try {
            file = File.OpenRead(path);
            return true;
        }
        catch (IOException e) {
            var errorCode = Marshal.GetHRForException(e) & ((1 << 16) - 1);
            isLocked = errorCode == 32 || errorCode == 33;
            condition = (isLocked && timeout > 0);

            if (condition) {
                // we only wait if the file is locked. If the exception is of any other type, there's no point on keep trying. just return false and null;
                timeout--;
                new System.Threading.ManualResetEvent(false).WaitOne(1000);
            }
        }
    }
    while (condition);

    file = null;
    return false;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top