2016-02-11 97 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");