Search code examples
c#subprocessworking-directory

Start subprocess in different folder


I have a button in my wpf app that starts timeout cmd before executing another set of commands. The problem is that I need to spawn that process in a different folder, so I can delete the folder my WPF app is in.

I can delete all the files in the said folder including the wpf app, but the folder itself remains locked because the hidden cmd processes are spawned inside it.

I've tried adding workingdirectory, but doesn't seem to work. Still spawns the processes in the same place.

public void HiddenProcess(string processName, string commandLineArgs)
{
    Process process = new Process();
    process.StartInfo.FileName = processName;
    process.StartInfo.Arguments = commandLineArgs;
    process.StartInfo.CreateNoWindow = false;
    process.StartInfo.ErrorDialog = false;
    process.StartInfo.UseShellExecute = true;
    process.StartInfo.WorkingDirectory = @"%Documents%";
    process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    process.Start();
}

private void Rtvp_Click(object sender, RoutedEventArgs e)
{
    HiddenProcess("cmd", "/c mkdir %USERPROFILE%\\Documents\\tasks");
    HiddenProcess("cmd", "/c attrib +h %USERPROFILE%\\Documents\\tasks /s /d");
    HiddenProcess("cmd", "/c timeout -t 600 /nobreak&" + somecommand)
}

I want to know if anything can be done so any process is started with HiddeProcess method can be started in a different folder.


Solution

  • If you set the UseShellExecute to false the working directory will be the directory for the new process, as said in the doc here.