I am trying to execute a OS command through C#. I have the following code taken from this webpage:
//Execute command on file
ProcessStartInfo procStart =
new ProcessStartInfo(@"C:\Users\Me\Desktop\Test\System_Instructions.txt",
"mkdir testDir");
//Redirects output
procStart.RedirectStandardOutput = true;
procStart.UseShellExecute = false;
//No black window
procStart.CreateNoWindow = true;
//Creates a process
System.Diagnostics.Process proc = new System.Diagnostics.Process();
//Set start info
proc.StartInfo = procStart;
//Start
proc.Start();
but when I attempt to run the code I get the following error:
{"The specified executable is not a valid application for this OS platform."}
What am I doing wrong? I have tried this example as well but got the same issue.
The overload of the
ProcessStartInfo
constructor you are using expects an executable file name and parameters to pass to it - a.txt
file is not executable by itself.It sounds more like you want to execute a batch file with commands within the file. For that check this SO thread: How do I use ProcessStartInfo to run a batch file?
If you want to open up the file in Notepad, use:
If you want to write into the file :
If you have commands in the text file that you want to execute, just rename it to .bat and it should work (and presumably the contents do something with "mkdir testDir" as a parameter?)
You would target an executable or other file that has a specified opening application. You're targeting a text file; what you should do is target Notepad, and then supply the path to your text file as an argument:
Alternatively, if you mean for your text file to be executed, it needs to be made a .bat file.
You are trying to execute a TXT file. That's why you get
Because, well, the specified executable (TXT) is not a valid application for this OS platform.
Try setting the USESHELLEXECUTE member to TRUE instead of FALSE.
It worked for me - but I think this has reprocussions for certain users after publishing.
You are trying to execute this:
The shell has no clue how to "execute" a text file so the command fails.
If you want to execute this text file as a batch file, change file extension to
.bat
so the system understands it's a batch file, and then setUseShellExecute
so it does the default action for it (= runs it, in case of a batch file).