使用 Winform C# ,删除 exe 所在的文件夹



我有一个winform exe,它可以删除应用程序以及该应用程序具有的所需文件夹。但是我也想删除wform根文件夹。那么有没有一种方法可以做到这一点,因为我被告知无法删除其中运行 exe 的文件夹。那么是否有任何 TEMP 路径或类似的东西,我可以在其中复制卸载程序,以便它删除安装程序根文件夹以及在该过程完成后删除它本身。

谢谢

您可以运行不可见的 CMD 实例来为您执行删除操作:

ProcessStartInfo psi = new ProcessStartInfo("cmd.exe", 
    String.Format("/k {0} & {1} & {2}", 
        "timeout /T 1 /NOBREAK >NUL",
        "rmdir /s /q "" + Application.StartupPath + """,
        "exit"
    )
);
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
Process.Start(psi);

在应用程序即将关闭时执行上述代码,它将删除它所在的目录。

使用的命令:

timeout /T x /NOBREAK >NUL
    - Wait for a certain amount of time.
        /T x     - Wait for x seconds.
        /NOBREAK - Specifies that it shouldn't be interrupted by pressing Space or Enter.
        >NUL     - Don't output any messages to the console.
rmdir /s /q <path>
    - Removes the directory <path>.
        /s - Remove subfiles and subdirectories.
        /q - Don't ask for confirmation.
exit
    - Closes the CMD instance

重要提示:使用它时要非常小心,因为它会删除整个目录,无论其中有什么!

相关内容

最新更新