【问题标题】:File IO operations in .NET throws IO Exception.NET 中的文件 IO 操作引发 IO 异常
【发布时间】:2019-02-19 17:42:49
【问题描述】:

我有一个用 VB.NET 编写的代码,它包含两个文件操作,即 File.Exists()File.Delete(filepath),其中 filepath 是要删除的文件的路径。每当我运行此代码时,它第一次执行时都没有问题,如:-

如果 File.Exists 为真,则 File.Delete,但是,当我下次尝试对另一个文件执行相同操作时,就会出现此问题。说“某个进程正在使用该文件”。在这里,我唯一做的就是使用 File.Exists 和 File.Delete 操作。没有读取文件/流或复制/创建文件或打开/关闭文件。

谁能在这个话题上启发我并给我一些建议?

另外,我已经尝试了堆栈溢出的大多数建议,但无济于事。

编辑:- (使用的代码)

Dim dir As String = "C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/" 
Dim filePath As String = "C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/'somefile'"
Dim fileInfo As New FileInfo(filePath)


Try

    If Directory.Exists(dir) Then

       If File.Exists(filePath) Then

          File.Delete(filePath)

       End If

Catch ex As Exception

   Debug.WriteLine("Error: " + ex.Message)

End Try

【问题讨论】:

  • 您是否在第一次调用后立即调用第二个 Exists 并删除?
  • 是的,检查文件是否存在,如果存在则删除。但不是在第一次调用后,我有一个按钮调用由两个文件操作组成的函数。
  • 每次删除调用的路径是否相同(相同的文件)?根据文件系统,文件删除需要时间。如果你暂停它是否运行成功?
  • (我知道人们讨厌这个建议,但请尝试一下)尝试将Application.DoEvents 放在File.Exists 前面。它会强制线程同步,有时会赶上待处理的后台操作(如 file.close、flush 等)
  • 如果您发布代码,会员会更容易帮助您。

标签: .net vb.net


【解决方案1】:

我无法重新创建它。

测试

Private Shared prng As New Random
Private Sub Abuse()
    For x As Integer = 1 To 50
        FileTest()
    Next
    Debug.WriteLine("done")
End Sub

Private Sub FileTest()
    Dim b(2047 * 1024) As Byte
    prng.NextBytes(b)

    'setup a test folder
    Dim path As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
    Dim testF As String = IO.Path.Combine(path, "testƒ")
    If Not IO.Directory.Exists(testF) Then
        IO.Directory.CreateDirectory(testF)
    End If

    'create some files
    Dim fn() As String = {"one", "two", "three"}
    For Each f As String In fn
        Dim p As String = IO.Path.Combine(testF, f)
        p = IO.Path.ChangeExtension(p, "txt")
        Dim fs As IO.FileStream = IO.File.Create(p)
        fs.Write(b, 0, b.Length) 'write some data
        fs.Close()
        fs.Dispose()
    Next

    fn = IO.Directory.GetFiles(testF) 'retrieve files just created
    For Each f As String In fn
        If IO.File.Exists(f) Then
            IO.File.Delete(f)
        End If
        If IO.File.Exists(f) Then 'shouldn't exists
            IO.File.Delete(f)
        End If
    Next

    If IO.Directory.Exists(testF) Then
        IO.Directory.Delete(testF, True)
    End If
End Sub

【讨论】:

  • 对不起,这不是我要找的。我确实提到我没有使用任何打开/写入文件操作,因此无法执行文件关闭/处理。
猜你喜欢
  • 1970-01-01
  • 2016-02-25
  • 1970-01-01
  • 1970-01-01
  • 2015-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多