【发布时间】:2016-02-12 04:16:34
【问题描述】:
我必须删除带有应用程序 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 文件的解决方案。
希望得到帮助。谢谢。
【问题讨论】:
-
大部分是猜测,但也许您需要先更改当前工作目录? msdn.microsoft.com/en-us/library/…
-
在您的按钮单击事件处理程序上,如果 del == true... 在该 if 语句中检查文件夹中的文件是否未使用
-
@David 谢谢!我已经更改了工作目录,现在可以了。
-
@user5817386:太好了!我将在下面汇总一个答案,以便未来的用户可能更容易找到它。一会儿……
标签: c#