[聚合问答] .NET Process.Start default directory?

c# 2018-01-23 34 阅读

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?

6个回答

137

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);

2018-01-23
48

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 .

2018-01-23
8

Use the ProcessStartInfo.WorkingDirectory property.

Docs here.

2018-01-23
5

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.

2018-01-23
4

Use the ProcessStartInfo class and assign a value to the WorkingDirectory property.

2018-01-23
3

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.

2018-01-23

注:本文内容来自互联网,旨在为开发者提供分享、交流的平台。如有涉及文章版本等事宜,请你联系站长进行处理。