我必须用应用程序exe文件删除目录。 它看起来像这样:
- 从C:\ Folder \ App.exe
启动App.exe- App.exe将自身复制到C:\ User \ Temp \ Temp.exe
- App.exe正在关闭并运行Temp.exe
- Temp.exe正在删除App.exe和C:\ Folder目录
醇>
看起来不错但是当我将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 :(得分:1)
我怀疑问题是应用程序仍然从当前目录运行,即使它正在运行单独的可执行文件。例如,考虑命令行:
C:\SomeFolder>../AnotherFolder/SomeProgram.exe
虽然SomeProgram
可能在AnotherFolder
,但我我自己是"在" SomeFolder
因此,保持对它的引用。所以它不能被删除。
但是,您应该能够从代码中change the current working directory。像这样:
Directory.SetCurrentDirectory(@"C:\User\Temp");