【问题标题】:C# Unlocking directory and copying filesC#解锁目录和复制文件
【发布时间】:2016-02-12 04:16:34
【问题描述】:

我必须删除带有应用程序 exe 文件的目录。 它看起来像这样:

  1. 从 C:\Folder\App.exe 启动 App.exe
  2. App.exe 将自身复制到 C:\User\Temp\Temp.exe
  3. App.exe 正在自行关闭并运行 Temp.exe
  4. 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#


【解决方案1】:

我怀疑问题在于应用程序仍在当前目录中运行,即使它正在运行单独的可执行文件。例如,考虑一个命令行:

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

虽然SomeProgram 可能在AnotherFolder 中,但我我自己“在”SomeFolder 中,因此保持对它的引用。所以无法删除。

不过,您应该可以通过代码change the current working directory。像这样的:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 2020-01-12
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多