2010-11-27 49 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

它看起來像你使用一個單獨的進程寫出文件 - 也許這是仍然使用該文件,當你試圖刪除。

我建議抓住並處理異常來解決問題。

相關問題