1

I created this simple .bat File:

mstsc C:\Temp\example.rdp
DEL C:\Temp\example.rdp

The normal behaviour of the .bat file is to open the rdp dialog and wait til I close the RDP connection. After that the .rdp file will be deleted.

This works perfect for me.

Now I want to open the .bat file from my C# WPF project with a click on a button.

Process p = new Process();
p.StartInfo.FileName = @"cmd.exe";
p.StartInfo.WorkingDirectory = @"C:\Temp";
p.StartInfo.Arguments = "/k " + "example.bat";
p.Start();

I tried all different arguments but the result is always the same the .bat file won't wait for the mstsc command to finish.

Do you have an idea to get this work?

Edit: I want the .bat file because i want to delete the .rdp file although my program isn't running and i don't want to close all rdp connections when i close the program.

LordWilmore
  • 2,829
  • 2
  • 25
  • 30
Mynar
  • 11
  • 2
  • Try adding `p.WaitForExit()`. Though, I'm not sure why that would be needed since presumably you aren't exiting the WPF application. More likely the process isn't exiting, maybe missing environment variables? Try hooking into the standard error output to see if there is something there. Similar to hooking into stdout: https://stackoverflow.com/questions/15234448/run-shell-commands-using-c-sharp-and-get-the-info-into-string/15234481#15234481 – P.Brian.Mackey Apr 19 '18 at 14:59
  • What exactly is the behavior you're seeing when you run this code? It works fine for me in a console application. – Rufus L Apr 19 '18 at 15:40
  • The mstsc command can't be executed because the .rdp file is already deleted by the second command. There is maybe a problem between a GUI project and a cmd invocation. – Mynar Apr 19 '18 at 15:47

2 Answers2

1

Why are you not directly running mstsc?

Process.Start("mstsc", "dir-to-blah.rdp").WaitForExit();
File.Delete("dir-to-blah.rdp");
  • I want the opportunity to delete the .bat file when my program isn't running. I don't want to close all rdp Sessions when my program is closed. – Mynar Apr 19 '18 at 15:07
  • I'd suggest writing the rdp file to the TEMP directory and letting windows cleanup handle that for you. – Alexander Ivanov Apr 19 '18 at 15:23
0

try using the "start" command.

start is documented here: https://ss64.com/nt/start.html

you should be able to do something like

Process p = new Process();
p.StartInfo.FileName = @"cmd.exe";
p.StartInfo.WorkingDirectory = @"C:\Temp";
p.StartInfo.Arguments = "start /w" + "/k " + "example.bat";
p.Start();

(as usual, my code is completely untested - leaving the final solution up to the OP)

theGleep
  • 1,179
  • 8
  • 14