I would like to start a new process but I need it to use a different folder for AppData. In a windows batch file you can do it like this:
set APPDATA=C:\MyDataFolder
It will set the AppData for any program launched in the batch file, so how can I do this in C#?
You can add environment variables to the ProcessStartInfo:
ProcessStartInfo p = new ProcessStartInfo("some_executable.exe");
p.UseShellExecute = false; // apparently required when adding environment variables
p.EnvironmentVariables.Add("APPDATA", #"C:\MyDataFolder");
Process.Start(p);
Off the top of my head: Environment.SetEnvironmentVariable
According to MSDN:
Creates, modifies, or deletes an environment variable stored in the
current process.
Current process being the operative word...
Related
I have created a script using Python2.7 and compiled it using pyinstaller into an exe of the same name, in this case "GeneralStats.py" turns into "GeneralStats.exe" using --onefile and -w arguments.
When called with C# I use:
var pythonDirectory = (Directory.GetCurrentDirectory());
var filePathExe1 = Path.Combine(pythonDirectory + "\\Python\\GeneralStats.exe");
Process.Start(filePathExe1);
When called outside of C#, so in my local files I can run the .exe and the result is a text file with lots of values in (Running correctly).
However, when ran with C# in this format, I get an error that "GeneralStats returned -1!"
Which I have had issues with before, but it was a simple python error that when I returned to my code and ran it, I would receive an error that I overlooked.
This time my python code returns no errors and works outside of C#.
Any ideas of why this could be? I can provide any code or file directories necessary, please just ask if you feel it would help with debugging.
EDIT:
Solved by removing:
var filePathExe1 = Path.Combine(pythonDirectory + "\\Python\\GeneralStats.exe");
Process.Start(filePathExe1);
And replacing with:
ProcessStartInfo _processStartInfo = new ProcessStartInfo();
_processStartInfo.WorkingDirectory = Path.Combine(pythonDirectory + "\\Python");
_processStartInfo.FileName = #"GeneralStats.exe";
_processStartInfo.CreateNoWindow = true;
Process myProcess = Process.Start(_processStartInfo);
You need to set the working directory for the Process - it is probably trying to load files from its working directory but isn't finding them.
See, e.g. this:
Use the ProcessStartInfo.WorkingDirectory property to set it prior to starting the process. If the property is not set, the default working directory is %SYSTEMROOT%\system32.
Set it to the path where GeneralStats.exe is.
I have console application 1 which write text to file and it is in C:/app1
using (StreamWriter k = new StreamWriter("777.txt"))
k.WriteLine("aa");
I have another console application 2, c:/app2, which start console application 1
System.Diagnostics.Process.Start("c:/app1/app1.exe");
For some reason, when I run application 2, the output 777.txt will be in folder2 instead of folder1. When I run application 1 from windows explorer, the output 777.txt will be in folder1.
I look and tried to add environment.path but it didn't solve the problem.
Please try the following:
ProcessStartInfo startInfo = new ProcessStartInfo(#"c:\app1\app1.exe");
startInfo.WorkingDirectory= #"c:\app1";
Process.Start(startInfo);
Your application 1 is using a relative path, not a rooted path. That path is relative to the "current directory", not the "path" environment variable.
Process can accept a ProcessStartInfo instance which includes a property to define the current directory. You'll want to set that to the location of application 1 before starting it.
you should replace your "777.txt" with AppDomain.CurrentDomain.BaseDirectory & "777.txt"
I am trying to set environment variable from a console application by executing it from my windows application. I invoke console application and send the value of environment variable as parameter to it, then set the thread to wait for 10 seconds to proceed with next execution.
In the next step i try to load a new .exe which reads the value set to the environment variable.
The exe will not read the new value and continue to refer the value set earlier.
Once the solution of application is closed and open then it reads the new value i.e reload the vshost.
betting you set up the variable only for the current process. You should try this overload of the Environment.SetEnvironmentVariable method :
Environment.SetEnvironmentVariable("YourVar", "YourValue",
EnvironmentVariableTarget.User);
[Edit] Re-Reading your question, you said in the title "same process", and in the question "new exe". In term of Env varialble, spanning a new process implies a new process scope for env variables. They won't share env variables with process scope just because it's the same executable. Maybe you should explain what you are trying to do at a higher level.
[Edit2] not sure to understand why it fails... But you can specify env variable when spawning process using a ProcessStartInfo.EnvironmentVariables Property
Basically, it can be (not tested) :
var psi = new ProcessStartInfo {
FileName="yourExe"
};
psi.EnvironmentVariables.Add("YourVariable","YourValue");
var process = Process.Start(psi);
I am using the following code to fire the iexplore process. This is done in a simple console app.
public static void StartIExplorer()
{
var info = new ProcessStartInfo("iexplore");
info.UseShellExecute = false;
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.RedirectStandardError = true;
string password = "password";
SecureString securePassword = new SecureString();
for (int i = 0; i < password.Length; i++)
securePassword.AppendChar(Convert.ToChar(password[i]));
info.UserName = "userName";
info.Password = securePassword;
info.Domain = "domain";
try
{
Process.Start(info);
}
catch (System.ComponentModel.Win32Exception ex)
{
Console.WriteLine(ex.Message);
}
}
The above code is throwing the error The system cannot find the file specified. The same code when run without specifying the user credentials works fine. I am not sure why it is throwing this error.
Can someone please explain?
Try to replace your initialization code with:
ProcessStartInfo info
= new ProcessStartInfo(#"C:\Program Files\Internet Explorer\iexplore.exe");
Using non full filepath on Process.Start only works if the file is found in System32 folder.
You can't use a filename like iexplore by itself because the path to internet explorer isn't listed in the PATH environment variable for the system or user.
However any path entered into the PATH environment variable allows you to use just the file name to execute it.
System32 isn't special in this regard as any directory can be added to the PATH variable. Each path is simply delimited by a semi-colon.
For example I have c:\ffmpeg\bin\ and c:\nmap\bin\ in my path environment variable, so I can do things like new ProcessStartInfo("nmap", "-foo") or new ProcessStartInfo("ffplay", "-bar")
The actual PATH variable looks like this on my machine.
%SystemRoot%\system32;C:\FFPlay\bin;C:\nmap\bin;
As you can see you can use other system variables, such as %SystemRoot% to build and construct paths in the environment variable.
So - if you add a path like "%PROGRAMFILES%\Internet Explorer;" to your PATH variable you will be able to use ProcessStartInfo("iexplore");
If you don't want to alter your PATH then simply use a system variable such as %PROGRAMFILES% or %SystemRoot% and then expand it when needed in code. i.e.
string path = Environment.ExpandEnvironmentVariables(
#"%PROGRAMFILES%\Internet Explorer\iexplore.exe");
var info = new ProcessStartInfo(path);
Also, if your PATH's dir is enclosed in quotes, it will work from the command prompt but you'll get the same error message
I.e. this causes an issue with Process.Start() not finding your exe:
PATH="C:\my program\bin";c:\windows\system32
Maybe it helps someone.
I had the same problem, but none of the solutions worked for me, because the message The system cannot find the file specified can be misleading in some special cases.
In my case, I use Notepad++ in combination with the registry redirect for notepad.exe. Unfortunately my path to Notepad++ in the registry was wrong.
So in fact the message The system cannot find the file specified was telling me, that it cannot find the application (Notepad++) associated with the file type(*.txt), not the file itself.
I know it's a bit old and although this question have accepted an answer, but I think its not quite answer.
Assume we want to run a process here C:\Program Files\SomeWhere\SomeProcess.exe.
One way could be to hard code absolute path:
new ProcessStartInfo(#"C:\Program Files\SomeWhere\SomeProcess.exe")
Another way (recommended one) is to use only process name:
new ProcessStartInfo("SomeProcess.exe")
The second way needs the process directory to be registered in Environment Variable Path variable. Make sure to add it in System Variables instead of Current User Variables, this allows your app to access this variable.
You can use the folowing to get the full path to your program like this:
Environment.CurrentDirectory
I'm firing off a Java application from inside of a C# .NET console application. It works fine for the case where the Java application doesn't care what the "default" directory is, but fails for a Java application that only searches the current directory for support files.
Is there a process parameter that can be set to specify the default directory that a process is started in?
Yes!
ProcessStartInfo Has a property called WorkingDirectory, just use:
...
using System.Diagnostics;
...
var startInfo = new ProcessStartInfo();
startInfo.WorkingDirectory = // working directory
// set additional properties
Process proc = Process.Start(startInfo);
Use the ProcessStartInfo.WorkingDirectory property to set it prior to starting the process. If the property is not set, the default working directory is %SYSTEMROOT%\system32.
You can determine the value of %SYSTEMROOT% by using:
string _systemRoot = Environment.GetEnvironmentVariable("SYSTEMROOT");
Here is some sample code that opens Notepad.exe with a working directory of %ProgramFiles%:
...
using System.Diagnostics;
...
ProcessStartInfo _processStartInfo = new ProcessStartInfo();
_processStartInfo.WorkingDirectory = #"%ProgramFiles%";
_processStartInfo.FileName = #"Notepad.exe";
_processStartInfo.Arguments = "test.txt";
_processStartInfo.CreateNoWindow = true;
Process myProcess = Process.Start(_processStartInfo);
There is also an Environment variable that controls the current working directory for your process that you can access directly through the Environment.CurrentDirectory property .
Just a note after hitting my head trying to implement this.
Setting the WorkingDirectory value does not work if you have "UseShellExecute" set to false.
Use the ProcessStartInfo.WorkingDirectory property.
Docs here.
The Process.Start method has an overload that takes an instance of ProcessStartInfo. This class has a property called "WorkingDirectory".
Set that property to the folder you want to use and that should make it start up in the correct folder.
Use the ProcessStartInfo class and assign a value to the WorkingDirectory property.