2010-11-27 55 views
0

我正在使用My.Computer.Filesystem.WriteAllBytes将存储在我的应用程序资源中的可执行文件写出到它的启动目录中。运行可执行文件后,我将其删除。一切工作正常;然而,我会无缘无故地得到一个UnauthorizedAccessException。得到例外之后,我可以手动删除文件而没有任何问题。下面是完整的代码:IO.File.Delete Random UnauthorizedAccessException

' 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 + """ """ + 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 

什么困扰我的是,我从字面上只是写出来的可执行文件,并没有别的也可能会被使用。我检查了文件属性,它不是只读的。我的应用程序也以管理员身份运行。可能是什么问题呢?

回答

3

您不会等待进程退出,因此当您尝试删除文件时它仍在运行。请参阅过程。 WaitForExit

+0

好啊,我不能相信我忽略了这一点。我用MAD.WaitForExit()替换了MAD.Close(),一切似乎都很好!谢谢! – Steven 2010-11-28 01:13:01

1

它看起来像你使用一个单独的进程写出文件 - 也许这是仍然使用该文件,当你试图删除。

我建议抓住并处理异常来解决问题。