>確定性文件鎖定在C#>
中檢查c#開發人員在嘗試保存之前嘗試訪問文件時經常遇到“通過另一個進程中使用的文件”錯誤。儘管例外處理是標準實踐,但對於某些應用程序來說,更可預測的方法是可預測的。
可以使用和FileInfo.Open
和FileAccess.Read
來實現這一點。 成功的文件打開(無例外)表明該文件可用。 相反,FileShare.None
表示鎖。 IOException
>
<code class="language-csharp">protected virtual bool IsFileLocked(FileInfo file) { // Attempt to open the file for reading with exclusive access try { using (FileStream stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None)) { // Successful opening; file is not locked return false; } } catch (IOException) { // File is locked return true; } }</code>此方法提供了一種確定的文件鎖定檢測方法,以避免依賴異常。 但是,至關重要的是要記住這僅適用於未使用寫入訪問打開的文件
>的文件。 即使文件已解鎖,嘗試與一起使用>也將始終失敗。
以上是可以在不使用異常的情況下在C#中檢查文件鎖定嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!