Open txt file from C# application - c#

The following code is suppose to open CMD from my C# application and open the file text.txt.
I tried to set the file path as an environment variable but when notepad opens it looks for %file%.txt instead of text.txt
Any idea why?
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents=false;
proc.StartInfo.EnvironmentVariables.Add("file", "c:\\text.txt");
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.FileName = "notepad";
proc.StartInfo.Arguments="%file%";
proc.Start();
proc.WaitForExit();
Console.WriteLine(proc.ExitCode);

If your purpose is to start the editor with a .txt file (like the title of the question says) just use:
Process.Start("C:\\text.txt")

The short version is that I suspect you are going to have to pass the arg more directly, i.e.
proc.StartInfo.Arguments = #"""c:\text.txt""";
Although you can set environment variables (for use within the process), I don't think you can use them during the process start.

What are you trying to accomplish with %file%? The command line argument for notepad.exe is the file you want to open. You need to do something like this:
proc.StartInfo.Arguments = "c:\\text.txt";

set UseShellExecute = true
that way it should use the cmd.exe processor to expand the %file% variable

One obvious problem is that you have UseShellExecute set false. This means you are executing notepad directly without passing via the command shell cmd.exe. Therefore environment variables aren't being expanded.
I'm not sure what you're trying to achieve (why do you need to add an environment variable?) but the following would work:
System.Diagnostics.Process proc =
new System.Diagnostics.Process();
proc.EnableRaisingEvents = false;
proc.StartInfo.EnvironmentVariables.Add("file", "c:\\text.txt");
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.Arguments = "/c notepad %file%";
proc.Start();
proc.WaitForExit();

Try this:
proc.StartInfo.Arguments = System.Environment.GetEnvironmentVariable("file");

Perhaps it has to do with how the StartInfo.Arguments work. If you can't find anything better, this worked for me:
proc.StartInfo.FileName = "cmd";
proc.StartInfo.Arguments="/c notepad %my_file%";

I am willing to bet you need to set WorkingDirectory to get this to work. NOTEPAD.exe is usually located in %SYSTEMROOT% (C:\windows) however the default is %SYSTEMROOT%\system32. Try out the below.
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents=false;
proc.StartInfo.WorkingDirectory = "%SYSTEMROOT%";
proc.StartInfo.EnvironmentVariables.Add("file", "c:\\text.txt");
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.FileName = "notepad";
proc.StartInfo.Arguments="%file%";
proc.Start();
proc.WaitForExit();
Console.WriteLine(proc.ExitCode);

Related

Process Arguments not being run

I'm trying to start a local instance of notepad with a text file to try out c# cmd line arguments for eventual use in a remote connection script. I'm using System.Diagnostics.Process, but the StartInfo.Arguments doesn't actually run completely and open the notepad instance.
var p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = #"cd\ start notepad C:\test\testcmdline.txt";
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.Start();
The window opens at root, which tells me the cd\ is working, but the "start notepad" does not seem to be running.
Am I missing something about the structure of StartInfo.Arguments?
EDIT: I'm trying to figure out how to run a python script on a remote server, and using this as a test for running things in cmd in c#. While it's fine to run this in notepad, I'm not sure if the principle would carry over to the eventual implementation of running a python script remotely so I'm attempting to learn how to run items through cmd in C# in general.
I ended up using the more simple 2 arg Process.Start.
string cmdText;
cmdText = #"/C C:\test\testcmdline.txt";
Process.Start("cmd.exe", cmdText);
Try adding /c in the beginning of the Arguments.
Or the above task can be done as below
var process = new ProcessStartInfo
{
FileName = "cmd.exe",
UseShellExecute = false,
WindowStyle = ProcessWindowStyle.Hidden,
Arguments = #"/c start notepad C:\test\testcmdline.txt"
};
Process.Start(process );

how to hide windows host script c#.net

I need hide hide Windows host script after this code:
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 slmgr.vbs /dlv";
process.StartInfo = startInfo;
process.Start();
Does anyone know how I could do this?
If you are talking about just hiding the window completely then you are missing setting the CreateNoWindow property.
startInfo.CreateNoWindow = true;
Instead of firing up an additional command-prompt, use cscript.exe to execute your VB script. If you do it this way you won't have to worry about the shell figuring out how to execute you vbs file and you won't get an additional command-line window.
startInfo.FileName = "cscript.exe";
startInfo.Arguments = "slmgr.vbs /dlv";
If the executable that is creating this process is not in the same directory as slmgr.vbs, you'll also need to set the full path to the file in the arguments, or set the working directory that the process runs in.
// Example path where your scripts could reside.
startInfo.WorkingDirectory = #"C:\PathToMyScripts\VBScripts\";
You probably want to redirect the output as well so you can log it somewhere.
Thank You for mr.BrutalDev
the second step
change startInfo.Arguments = "slmgr.vbs /dlv";
to startInfoent.Arguments = "C:\\Windows\\System32\\slmgr.vbs /dlv";

Commandline Arguments in C#

Hello again Stackoverflow community,
Today I am trying to execute an application with commandline parameters in C#, that not realy difficult like I tried
Process.Start(foldervar + "cocacola.exe", "pepsi.txt");
Cocacola.exe writes and Log in its current folder. In my commandline I write it manually like this
C:\myfolder>cocacola.exe pepsi.txt
Works wonderful but if I try it in C# a total fail.
I read that C# parses the command as C:\myfolder>cocacola pepsi.txt, without the ".EXE" ending. And I tested it manually without the ending, and this does not work.
Now, my question is what is the correct way to get C# executing it C:\myfolder>cocacola.exe pepsi.txt with the ".EXE"
use ProcessStartInfo
http://www.dotnetperls.com/process-start
example:
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.WorkingDirectory=#"c:\someplace";
proc.StartInfo.FileName="cocacola.exe";
proc.StartInfo.Arguments="pepsi.txt";
proc.Start();
proc.WaitForExit();
here is docs on the StartInfo properties:
http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.aspx
Try setting the StartInfo properties.
Process process = new Process();
process.StartInfo.FileName = #"C:\myfolder\cocacola.exe";
process.StartInfo.Arguments = #"C:\myfolder\pepsi.txt";
process.Start();
ProcessStartInfo has the WorkingDirectory property you should set to C:\myfolder
see: http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.workingdirectory.aspx
You need to set the working directory first
string foldervar = #"C:\myfolder";
Process process = new Process();
process.StartInfo.WorkingDirectory = foldervar;
process.StartInfo.FileName = #"cocacola.exe";
process.StartInfo.Arguments = #"pepsi.txt";
process.Start();
Setting the WorkingDirectory is equivilent to cding into the proper directory before running programs. It's what relative paths are relative to.

Diagnostics.Process - Dump output to file

Hi I need to write the result of a mysqldump to a file with a standard windows commands.
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents = false;
proc.StartInfo.WorkingDirectory = "sample directory";
proc.StartInfo.FileName = "mysqldump";
proc.StartInfo.Arguments = "-u root -pPassword --all-databases > db.sql";
proc.StartInfo.RedirectStandardOutput = false;
proc.StartInfo.UseShellExecute = false;
proc.Start();
proc.WaitForExit();
But it doesn't write to file this way...
I don't want to read the output and then write it to file, since mysqldump output can become really big...
Any solutions?
Try executing through cmd.exe and enquote the command to keep your program from gobbling up the redirect:
proc.StartInfo.FileName = "cmd.exe";
proc.startinfo.Arguments =
"/c \"mysqldump -u root -pPassword --all-databases\" > db.sql"
If it's a lot of output you can use the proc.OutputDataReceived event, in the event handler just write the output to your file.
Read the MSDN article here
For piped output you may need ShellExecute to be true. If that doesnt work, you may had to pipe it yourself (i.e. either handle the data events, or have an async read/write loop), but the size shouldn't matter since you should only be reading small chunks of it at any time.
Pretty much on similar lines, but written in VB.NET. Convert it and you should be good... Link

Redirecting console output to another application

So say I run my program:
Process proc = new Process();
proc.StartInfo.FileName = Path.GetDirectoryName(Application.ExecutablePath)
+ #"\Console.exe";
proc.Start();
And then wish to output my console stream to this application, how would I go about doing so?
So say I have:
Console.WriteLine("HEY!");
I want that to show up in program that I ran's console. I know I have to redirect the output using
Console.SetOut(TextWriter);
But I have no idea how I would go about making it write to the other program.
I can see how I could do it if I were running my main program from Console.exe using RedirectStandardInput.. but that doesn't really help :P
RedirectStandardInput makes Console.exe take its input from a stream which you can access in the main program. You can either write directly to that stream, or use SetOut to redirect console output there...
Process proc = new Process();
proc.StartInfo.FileName = Path.GetDirectoryName(Application.ExecutablePath)
+ #"\Console.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardInput = true;
proc.Start();
proc.StandardInput.WriteLine("Hello");
Console.SetOut(proc.StandardInput);
Console.WriteLine("World");
EDIT
It's possible that Console.exe doesn't cope well with having data piped into it rather than entered interactively. You could check this from the command line with something like
echo "Hello" | Console.exe
If that doesn't do what you expect, redirecting your program's output won't either. To test your program without worrying about the target program, you could try
proc.StartInfo.FileName = #"cmd";
proc.StartInfo.Arguments = #"/C ""more""";
If that displays the text that you write to it, then the problem is on the receiving end.
RedirectStandardInput isn't the problem. Console is the problem.
StreamWriter myConsole = null;
if (redirect)
{
Process proc = new Process();
proc.StartInfo.FileName = Path.GetDirectoryName(Application.ExecutablePath)
+ #"\Console.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardInput = true;
proc.Start();
myConsole = myProcess.StandardInput;
}
else
myConsole = Console.Out;
Then just use myConsole as you would Console.
You need to use Process.StandardOutput and Process.StandardInput. Check out this article from MSDN, which may help point you into the right direction: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx
By the way, a much easier way to do what you are doing can be found here, as an accepted answer to a similar SO question: c# redirect (pipe) process output to another process

Categories

Resources