我在客戶端系統上遇到問題。在試圖用示例代碼重現它時,我已經轉載了它。UnauthorizedAccessException在使用FileStream刪除後創建文件
這裏的示例代碼
Imports System.IO
Public Class Form1
Private _lock As New Object
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim t As New Threading.Thread(AddressOf createFile)
With t
.IsBackground = True
.Name = Guid.NewGuid.ToString
.Start()
End With
End Sub
Private Sub createFile()
Dim path As String = "D:\SomeFile.txt"
For i As Integer = 0 To 1000
SyncLock _lock
If File.Exists(path) Then File.Delete(path)
Using fs As New FileStream(path, FileMode.CreateNew)
End Using
End SyncLock
Next
End Sub
End Class
只需運行該代碼,然後單擊按鈕3-4次,注意的異常,如在下面的截圖:
這樣做的堆棧跟蹤例外是:
System.UnauthorizedAccessException was unhand led消息=訪問 路徑'D:\ SomeFile.txt'被拒絕。 Source = mscorlib StackTrace: at System.IO .__ Error.WinIOError(Int32 errorCode,String maybeFullPath) at System.IO.FileStream.Init(String path,FileMode mode,FileAccess access,Int32 rights,Boolean useRights,FileShare share, Int32 bufferSize,FileOptions options,SECURITY_ATTRIBUTES secAttrs, String msgPath,Boolean bFromProxy,Boolean useLongPath) at System.IO.FileStream..ctor(String path,FileMode mode,FileAccess access,FileShare share,Int32 bufferSize,FileOptions options,String msgPath,Boolean bFromProxy) at System.IO.FileStream..ctor(String path,FileMode mode) at WindowsApplication1.Form1.createFile()in C:\ Users \ premjeet.singh \ Desktop \ WindowsApplication1 \ WindowsApplication1 \ Form1.vb :行在System.Threading.ThreadHelper.ThreadStart_Context(對象狀態) 在System.Threading.ExecutionContext.runTryCode(對象的UserData) 在System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode 代碼,CleanupCode backoutCode,對象的UserData) 在System.Threading.ExecutionContext.RunInternal(的ExecutionContext 的ExecutionContext,ContextCallback回調,對象狀態) 在System.Threading.ExecutionContext.Run(的ExecutionContext的ExecutionContext,ContextCallback回調,對象的狀態,布爾 ignoreSyncCtx) 在System.Threading.ExecutionContext .Run(ExecutionContext executionContext,ContextCallback回調,Object狀態) at Sys tem.Threading.ThreadHelper.ThreadStart()的InnerException:
任何人都可以讓我知道這個UnauthorizedAccessException例外,因爲該文件的原因創建新的人之前已被刪除,以及如何解決?
這似乎是對問題的真正解釋,非常感謝Hans the Great ...... :) – prem 2015-02-11 11:29:15