Open txt file from c # application

The following code should open CMD from my C # application and open the text.txt file.

I tried to set the file path as an environment variable, but when notepad opens, it searches 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); 
+4
source share
8 answers

If your goal is to start an editor with a .txt file (for example, the title of a question), simply use:

 Process.Start("C:\\text.txt") 
+10
source

The short option is that I suspect that you will have to pass the argument directly, i.e.

  proc.StartInfo.Arguments = @"""c:\text.txt"""; 

Although you can set environment variables (for use in the process), I do not think you can use them during the start of the process.

+3
source

What are you trying to do 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"; 
+2
source

One obvious problem is that you have UseShellExecute false set. This means that you execute the notepad directly without going through the cmd.exe command shell. Therefore, environment variables do not expand.

I'm not sure what you are trying to achieve (why do you need to add an environment variable?), But the following will 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(); 
+1
source

set UseShellExecute = true

therefore, it should use the cmd.exe processor to expand the% file% variable

+1
source

Try the following:

 proc.StartInfo.Arguments = System.Environment.GetEnvironmentVariable("file"); 
0
source

Perhaps this is due to how StartInfo.Arguments works. If you can't find anything better, this worked for me:

 proc.StartInfo.FileName = "cmd"; proc.StartInfo.Arguments="/c notepad %my_file%"; 
0
source

I bet you need to install WorkingDirectory to get this to work. NOTEPAD.exe is usually located in % SYSTEMROOT% (C: \ windows) , but by default it is % SYSTEMROOT% \ system32 . Try 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); 
0
source

All Articles