开发者

IO.File.Delete Random UnauthorizedAccessException

I'm using My.Computer.Filesystem.WriteAllBytes to write out an executable stored in my application's resources to it's startup directory. After running the executable, I then delete it. Everything works fine; however, I'll randomly get an UnauthorizedAccessException for no reason. After getting the exception, I can manually delete the file with no problem. Here's the full code:

' Convert MP3
' First, copy out converter
Dim Path = New IO.FileInfo(SoundPath)
Try
    My.Computer.FileSystem.WriteAllBytes(Application.StartupPath + "\converter.exe", My.Resources.madplay, False)
Catch ex As Exception
    MessageBox.Show(ex.ToString, "Report", MessageBoxButtons.OK)
    Exit Sub
End Try
' Set up process
Dim MAD As New Process
' Set process info
Dim output As String = IO.Path.GetFileNameWithoutExtension(Path.FullName) + ".wav"
Dim input As String = Path.FullName
Dim adjust As String = barVolumeAdjust.Value.ToString
Dim hz As String = "15000"
With (MAD.StartInfo)
    .FileName = Application.StartupPath + "\converter.exe"
    .Arguments = "-v -a " + adjust + " -R " + hz + " -o """ + output + """ 开发者_StackOverflow社区""" + input + """"
    .UseShellExecute = False
    .RedirectStandardInput = True
    .RedirectStandardError = True
    .RedirectStandardOutput = True
    .CreateNoWindow = True
End With
' Start
MAD.Start()
' Update title with output
Dim Line As String = MAD.StandardError.ReadLine
While Not Line Is Nothing
    Me.Text = Line
    Line = MAD.StandardError.ReadLine
End While
' Stop
MAD.Close()
' Delete MAD
Try
    IO.File.Delete(Application.StartupPath + "\converter.exe")
Catch ex As Exception
    MessageBox.Show(ex.ToString, "Report", MessageBoxButtons.OK)
End Try

What perplexes me is that I literally just wrote out the executable, and nothing else could possibly be using it. I've checked the file attributes and it's not read-only. My application is also running as an administrator. What could be the problem?


You do not wait for the process to exit, so it is still running when you attempt to delete the file. See Process.WaitForExit


It looks like your using a separate process to write out the file - perhaps this is still using the file when you try to delete.

I suggest catching and handling the exception to get around the problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜