我在客户端系统上遇到问题。在试图用示例代码重现它时,我已经转载了它。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