File.Copy 不工作 - 没有错误

File.Copy not working - no error

请看一下这段代码。由于某种我无法弄清楚的原因,File.Delete() 行没有被触发,我也没有收到错误。

    ' hard-coded for testing
    Dim path As String = "C:\Program Files (x86)\Test\Program\Program.exe"

    Dim appDir As String = My.Application.Info.DirectoryPath
    Dim iniPath As String = appDir & "\config.ini"
    Dim outputPath As String = appDir & "\output.ini"

    Dim textLine As String = ""
    Dim reader = File.OpenText(iniPath)
    Dim writer = New StreamWriter(outputPath)

    ' Read the lines in the ini file until the pathToExecutable line is found and write the path to that line
    While (InlineAssignHelper(textLine, reader.ReadLine())) IsNot Nothing
        If textLine.StartsWith("pathToExecutable=") Then
            writer.WriteLine("pathToExecutable=" & path)
        Else
            writer.WriteLine(textLine)
        End If
    End While

    reader.Dispose()
    reader.Close()
    writer.Dispose()
    writer.Close()

    File.Copy(outputPath, iniPath, True)
    File.Delete(outputPath) ' THIS ISN'T GETTING FIRED

    Return path

Ericosg 关于使用 try/catch 的建议让我想到了这个问题:我在我的代码中早些时候在 streamreader 中打开了文件,但从未在那里关闭它。

你说你没有收到错误,但如果你不实施异常处理,你很可能会收到错误并将其丢弃(双关语)。

在任何 System.IO.File 操作周围使用 try/catch,甚至更多,您可以实现特定的句柄并捕获特定的异常。

Try 
    File.Copy(outputPath, iniPath, True)
    File.Delete(outputPath) ' THIS ISN'T GETTING FIRED

Catch ioException As IOException
    'The specified file is in use.
    MessageBox.Show(ioException.Message)

Catch ex As Exception
    'Some other error apart for file in use.
    MessageBox.Show(ex.Message)

End Try