2016-02-11 69 views
0

我必須刪除具有應用程序exe文件的目錄。 它看起來是這樣的:C#解鎖目錄和複製文件

  1. 開始APP.EXE從C:\文件夾\ APP.EXE
  2. APP.EXE將自身複製到C:\用戶\ TEMP \ Temp.exe
  3. 應用.exe文件關閉本身並運行Temp.exe
  4. Temp.exe被刪除APP.EXE和C:\文件夾目錄

這看起來不錯,但是當我複製App.exe到Temp.exe,進程Temp.exe仍在使用C:\ Folder。 無論我做什麼,我開始鎖定我的目錄。

我做了一個表單應用程序,點擊按鈕檢查他們的行爲。

bool del = false; 
    public Form1(string[] args) 
    { 
     InitializeComponent(); 
     this.Text = Process.GetCurrentProcess().Id.ToString(); 
     if (args.Length > 0 && args[0] == "arg1") 
     { 
      Process proc = Process.GetProcessById(Convert.ToInt32(args[1])); 
      proc.Kill(); 
     } 
     else if (args.Length > 0 && args[0] == "arg2") 
     { 
      del = true; 
     } 
     else 
     { 
      string tempfile = Environment.GetEnvironmentVariable("TEMP") + "\\Temp.exe"; 
      File.Copy(Application.ExecutablePath, tempfile, true); 
      Process proc = new Process(); 
      proc.StartInfo.FileName = tempfile; 
      proc.StartInfo.Arguments = String.Format("arg1 {0}", Process.GetCurrentProcess().Id); 
      proc.Start(); 
      Application.Exit(); 
     } 
    } 
    private void button1_Click(object sender, EventArgs e) 
    { 
     if (del == true) 
     { 
      string ApplicationPath = @"C:\Folder"; 
      DirectoryInfo directory = new DirectoryInfo(ApplicationPath); 
      foreach (FileInfo file in directory.GetFiles()) file.Delete(); 
      Directory.Delete(ApplicationPath); 
     } 
     else 
     { 
      ProcessStartInfo Info = new ProcessStartInfo(); 
      Info.Arguments = "/C ping 127.0.0.1 -n 2 && \"" + Application.ExecutablePath + "\" arg2"; 
      Info.WindowStyle = ProcessWindowStyle.Hidden; 
      Info.CreateNoWindow = true; 
      Info.FileName = "cmd.exe"; 
      Process.Start(Info); 
     } 
    } 

在簡短的方式 - 我正在尋找解決方案,將刪除與父目錄啓動exe文件。

希望得到幫助。謝謝。

+0

大部分是猜測,但也許你需要先改變當前工作目錄? https://msdn.microsoft.com/en-us/library/system.io.directory.setcurrentdirectory – David

+1

在你的按鈕上單擊事件處理程序,如果del == true ...在if語句中檢查文件是否在該文件夾未被使用 –

+0

@大衛謝謝!我已經改變了工作目錄,現在很好。 – user5817386

回答

1

我懷疑問題是應用程序仍然是從當前目錄運行,即使它正在運行單獨的可執行文件。舉個例子,一個命令行:

C:\SomeFolder>../AnotherFolder/SomeProgram.exe 

雖然SomeProgramAnotherFolder,我自己上午「在」 SomeFolder,因此,保持開放的對它的引用。所以它不能被刪除。

儘管如此,您應該可以從代碼中獲得change the current working directory。就像這樣:

Directory.SetCurrentDirectory(@"C:\User\Temp");