IO.File.Delete在调试模式下工作,但在运行模式下抛出安全异常

时间:2014-03-20 22:45:07

标签: asp.net vb.net asp.net-web-api

有没有人见过IO.File方法与附加的调试器一起工作但在正常运行时没有的问题?

IO.File.Delete在运行时提供此异常,但如果调试器通过VS(以管理模式运行)附加,则不会。

“拒绝访问路径'C:\ AppName \ App_Data \ BodyPart_7416da26-4b8f-4d08-9a4a-fd3a9bf02327'。”

我已验证IIS_IUSRS对\ App_Data目录具有完全权限。 BodyPart_ *是ASP.Net生成的文件名,而不是子目录。

另一个人在StackOverflow上遇到此问题但尚未修复此问题。 (File.Delete() not working in run mode but only works in debug mode

我的代码:

''' <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 个答案:

答案 0 :(得分:1)

在调试模式下,没有为异步调用'ReadAsMultipartAsync'创建新线程,因此线程被阻塞,直到该方法完成。在发布模式下,它使用新线程进行异步调用,并且由于该方法在单独的线程上运行,因此其余代码仍在当前线程上进行处理。当您删除文件时,文件仍然被附加线程上的“ReadAsMultipartAsync”方法锁定。由于文件仍处于锁定状态,因此删除操作将失败。您需要等待'ReadAsMultipartAsync',以便在继续处理之前完成。

试试这个:

await Request.Content.ReadAsMultipartAsync(provider)