问题
Has anyone ever seen an issue where IO.File methods work with the debugger attached but not at normal run-time?
IO.File.Delete gives this exception at run-time but not if the debugger is attached via VS (which runs in admin mode).
"Access to the path 'C:\AppName\App_Data\BodyPart_7416da26-4b8f-4d08-9a4a-fd3a9bf02327' is denied."
I have verified IIS_IUSRS has full permissions on the \App_Data directory. BodyPart_* is a file name generated by ASP.Net, not a sub-directory.
One other person having this issue on StackOverflow but no fixes as of yet. (File.Delete() not working in run mode but only works in debug mode)
My code:
''' <summary>
'''Post file(s) and store it via VDocument WS
''' </summary>
<System.Web.Http.HttpPost>
<ActionNameAttribute("PostFiles")> _
Public Function PostFiles(<FromUri> fileGroupGuid As Guid) As HttpResponseMessage
Dim newFileIds As New List(Of Integer)
Dim filesToDelete As New List(Of String)
' Check if the request contains multipart/form-data.
If Not Request.Content.IsMimeMultipartContent() Then
Throw New HttpResponseException(HttpStatusCode.UnsupportedMediaType)
End If
Dim root As String = HttpContext.Current.Server.MapPath("~/App_Data")
Dim provider = New MultipartFormDataStreamProvider(root)
' Read the form data.
Request.Content.ReadAsMultipartAsync(provider)
For Each file As MultipartFileData In provider.FileData
'Store to VDoc Server
Dim vdocService As New wsdocument.vdocument
Dim vdocId As String
Dim sOrigFileName As String = "/" & file.Headers.ContentDisposition.FileName.Replace("""", "")
vdocId = vdocService.savedocument(IO.File.ReadAllBytes(file.LocalFileName), sOrigFileName, _
"FS Upload", "0", "0", "0", "0")
' Store the posted file reference in the database
Dim fileId As Integer = New Answer().StoreAnswerFileWithVDocumentId(fileGroupGuid.ToString, sOrigFileName, 0, file.Headers.ContentType.ToString, New Byte(-1) {}, 0, _
0, FSFileMode.RespondentAnswer, Convert.ToInt32(vdocId))
newFileIds.Add(fileId)
filesToDelete.Add(file.LocalFileName)
Next
For Each tempFile As String In filesToDelete
'delete the temp file
IO.File.Delete(tempFile)
Next
Return Request.CreateResponse(HttpStatusCode.Accepted, newFileIds)
End Function
回答1:
In debug mode a new thread is not getting created for the async call 'ReadAsMultipartAsync' and so the thread is blocked until that method completes. In release mode, it's using a new thread for the async call and since that method is running on a seperate thread, the rest of your code is still processing on the current thread. When you get to deleting the files, the files are still locked by the 'ReadAsMultipartAsync' method on the additional thread. Since the files are still locked, the delete will fail. You need to await the 'ReadAsMultipartAsync', so that it completes before you continue processing.
Try this:
await Request.Content.ReadAsMultipartAsync(provider)
来源:https://stackoverflow.com/questions/22546747/io-file-delete-works-in-debug-mode-but-throws-security-exception-in-run-mode