How to open notepad with cmd? - c#

I want to open notepad with CMD, using C# but the path has a space in it. I know that there are a lot of questions similar to this, but I couldn't get any of those solutions to work with my example. I do not know why. If anyone wants to help, it would be greatly appreciated.
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = #"/C START ""C:\Users\Dale\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Accessories\notepad.exe""";
process.StartInfo = startInfo;
process.Start();
There is no error message, but nothing happens in the command prompt, and notepad doesn't open. Another issue is that the command prompt is visible even though I added
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

You surely don't have the notepad application in your Start Menu, there's only a shortcut there. Usually notepad is located here:
C:\Windows\System32\notepad.exe
What might be misleading, is that clicking "Open file location" on the notepad icon in Start Menu takes you to the place when the shortcut is placed. However, you may notice that it's only a shortcut because of the little arrow icon in the corner. Then, you can right click and choose "Open file location" again - it will point you to the right place this time.

The safe and better approach is to go with
string notepad_path = System.Environment.SystemDirectory + "\notepad.exe";

C# is probably ignoring the double double quotes ie, the "".
Try escaping the quotes with backslash, ie:
startInfo.Arguments = #"/C START "\"C:\Users\Dale\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Accessories\notepad.exe\""";

I assume the path and all that is correct.
In C#, adding a # before a string takes care of special characters that otherwise would need an escape symbol in front of it (\).
#"/C START ""C:\Users\Dale\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Accessories\notepad.exe"""
This should expand to /C START ""C:\Users\Dale\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Accessories\notepad.exe"". I guess it has some problems finding that path. Maybe reducing the double quotes to one on each side will help.

Related

How do I create a string dynamically in C#?

I am developing an application for managing Personal Hotspot of a Laptop
(Windows of Course).
I'm having a little difficulty in changing the Hotspot Name.
Here is my Code:
//For CMD Command
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new
System.Diagnostics.ProcessStartInfo();
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.FileName = "CMD.exe";
startInfo.CreateNoWindow = true;
//Reading User Input in textBox1:
string name = textBox1.Text;
//CMD Argument:..., Which is currently written wrong to make it Easy to
//understand the problem
startInfo.Arguments = "/C netsh wlan set hostednetwork ssid="name";
process.StartInfo = startInfo;
process.Start();
Here, In the Arguments line, the syntax is wrong. The value assigned to Arguments should be a single string. I need to incorporate name, that has a dynamic value, with the rest of the string that is constant. How do I do that?
Unless I'm missing something here, seems to me that a simple string concatenation would do it:
startInfo.Arguments = "/C netsh wlan set hostednetwork ssid=" + name;
There are several ways you can create a dynamic string:
For your specific case, Concatenation is the best choice as your string is very simple.The reason you would choose this method for your case is because it is very light as compared to other methods and has a clean enough syntax.
startInfo.Arguments = "/C netsh wlan set hostednetwork ssid=" + name;
For anything more complicated, string.Format is a popular go to. You would generally use it to combine more complex strings than your example. This tutorial covers the subject thoroughly.
startInfo.Arguments = string.Format("/C netsh wlan set hostednetwork ssid={0}", name);
The release of C#6.0 included a neat feature: interpolated strings. It is for the most part just syntactic sugar for string.Format, where the line below is turned into the line above at compile time. There are subtle differences, but those are not important in this thread.
startInfo.Arguments = $"/C netsh wlan set hostednetwork ssid={name}";
And lastly, if you need to change a string more than a few times (I usually use the rule of 5 - i.e. a string changes more than 5 times), I would use the StringBuilder class. A great application, among many others, would be a long loop that modifies a certain string each iteration. See This Tutorial.
In this case, the Garbage Collector will thank you for a using a StringBuilder!

command execution in C#

I need to execute the following command, it works perfectly, if I execute it via command prompt, here the command line is using kodakprv.exe to send a print of a tiff file.
but when trying to execute it via c#, its not throwing any error but not sending the print either, tried to execute this command via xp_cmdshell in SQL, but it didn't work, in the xp_cmdshell documentation found that, quotes are not allowed for more then once, but kodakprv.exe print logic requires 3 pair of quotes
Please suggest can we use multiple quotes in C# while executing the command or suggest any better solution for it
String sCommand = "\"c:\\progra~1\\imagin~1\\kodakprv.Exe\" /pt \"D:\\SQLDev\\Dlls\\Testing.TIF\" \"\\\\Galactica\\C-Test1\"";
// Put your code here
System.Diagnostics.Process ExecuteCommand = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.Arguments = #" /c " + sCommand.ToString();
MessageBox.Show(startInfo.Arguments);
ExecuteCommand.StartInfo = startInfo;
ExecuteCommand.Start();
You don't need all those quotes. Only paths with spaces require quotes. None of your paths have spaces.
Shortnames, as you are using, may not exist (they can be turned off), or may not have the name you think. Windows does not preserve short names, only long names.
You are running your program via CMD. Unless your command line has redirection characters (as CMD handles redirection characters) then CMD is not required. You can start your program directly, which would be the preferred way (faster, less resources used).
Your window is set to hidden. Therefore you cannot see the message it is telling you. Unhide your window.
Your program will likely exit and close the window before you can read it. Either stick a &pause at the end of the command line sent to CMD, or read what is on both StdErr and StdOut as you specify to capture them in your code.

Running cmd commands

I run a cmd command in c# and somehow it usually crashes. I mean, when I work with smaller files (I run some kind of converter software) it almost always suceeds, but when I try it with larger ones it just crashes. I want to know where. And therefore I would like to run the command and see all the details, like the progress.
When I run it normally, by hand in command line, it writes like : Welcome to ... Progress : ... and so on. But how could I see that in C#? I only see the blank black stuff.
Here's my code. I tried to write out the StandardOutput, the StandardError, but it seems like its good. So my only chance is to see the details of the stuff running.
process = new System.Diagnostics.Process();
startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.FileName = "cmd.exe";
startInfo.WorkingDirectory = dir.Parent.FullName;
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardError = true;
process.StartInfo = startInfo;
process.Start();
process.StandardInput.WriteLine(#"make html");
k = new StreamReader(process.StandardOutput.BaseStream);
process.StandardInput.WriteLine(#"exit");
k.ReadToEnd();
Thank you guys, I hope you can help. Have a nice day!
EDIT: Now I see the output, by writing make html > output.txt
So my problem now is, why can I run exactly the same command from cmd, by hand, and why I cannot from C#
Thanks
You are on the right track for the redirection, you just have to hook up what you want to do with it...
Please check this post but here is a portion...
startinfo.OutputDataReceived += DOSOutputResultsHandler;
StringBuilder DOSOutputResults = new StringBuilder();
protected void DOSOutputResultsHandler(object sendingProcess,
System.Diagnostics.DataReceivedEventArgs outLine)
{
if (!string.IsNullOrEmpty(outLine.Data))
// track data into the NORMAL output string builder
DOSOutputResults.Append(Environment.NewLine + outLine.Data);
}
So now I have an answer, that worked for me.
I tried many ways to write out the output, and see where it crashes.
After a few turns I realized it starts working when I write out the output into a txt, with the following two methods:
I used the cmd: "make html > infooutput.txt" and "make html 2> infoerrors.txt".
I cannot explain why this works, but as I put these lines everywhere, where I called this command, it starts working.
Thank you very much for your help, you may find other great advices in the comment sections, for me they did not work properly.

Compile an .asm file through c# using cmd

I want to compile an .asm file placed in bin folder in the masm through c#.I have tried multiple methods like process.start but nothing helps.It opens the cmd but the command "ml" never executes.It either open the pwb.exe(MASM) or the 'file.asm' in notepad.I give these arguments to CMD "path\ml file.asm" which works fine manually.ml is a command used to compile .asm files. One of the method I used is following
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = #"C:\WINDOWS\system32\cmd.exe";
startInfo.Arguments = "C:\Users\Hassan\Documents\Visual Studio 2010\Projects\FYP\FYP\MASM611\BIN\ml file.asm";
process.StartInfo = startInfo;
process.Start();
If you want to start the process in this way, you'll need to put quotes round the path, due to the spaces:
startInfo.Arguments = #"""C:\Users\Hassan\Documents\Visual Studio 2010\Projects\FYP\FYP\MASM611\BIN\ml"" file.asm";
(In a verbatim string literal, you include double-quotes by doubling them.)
Alternatively, if ml is actually an executable (I know nothing about masm) you could just use:
startInfo.FileName = #"C:\Users\Hassan\Documents\Visual Studio 2010\Projects\FYP\FYP\MASM611\BIN\ml.exe";
startInfo.Arguments = "file.asm";
To start "cmd.exe" and run another program you need to use the /c switch.
/C Carries out the command specified by string and then terminates
So you would need:
startInfo.Arguments = "/c \"C:\Users\Hassan\Documents\Visual Studio 2010\Projects\FYP\FYP\MASM611\BIN\ml.exe\" file.asm";
I've added extra quotes for the space in the path.
If you don't need to run it via the command prompt - "cmd.exe" - then you can put the path to "ml.exe" in FileName and just pass the "file.ml" as the Arguments.

Mimic Windows' 'Run' window in .NET

I would like to mimic the Run command in Windows in my program. In other words, I would like to give the user the ability to "run" an arbitrary piece of text exactly as would happen if they typed it into the run box.
While System.Diagnostics.Process.Start() gets me close, I can't seem to get certain things like environment variables such as %AppData% working. I just keep getting the message "Windows cannot find '%AppData%'..."
You can use the Environment.ExpandEnvironmentVariables method to turn %AppData% into whatever it actually corresponds to.
Depending on what you're trying to do, you could also call CMD.EXE, which will expand your environment variables automatically. The example below will do a DIR of your %appdata% folder, and redirect the stdOut to the debug:
StreamReader stdOut;
Process proc1 = new Process();
ProcessStartInfo psi = new ProcessStartInfo("CMD.EXE", "/C dir %appdata%");
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
proc1.StartInfo = psi;
proc1.Start();
stdOut = proc1.StandardOutput;
System.Diagnostics.Debug.Write(stdOut.ReadToEnd());

Categories