Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

.net - Defining a working directory for executing a program (C#)

I am currently trying to get an executable to be launched from a specific folder.

The code I have below crashes the application oddly enough:

Process p = new Process();
p.StartInfo.WorkingDirectory = "dump";
p.StartInfo.FileName = s;
p.Start();

I debugged it, and it was saying it can't find the file to start, but the file / folder defintly exists, is my syntax bad?

The code below works, but a working directroy is not defined, so it can't find the executable

Process.Start(@"dump", s);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The working directory that you set ("dump") is relative to the current working directory. You might want to check the current working directory.

You should be able to set the working directory to the executing assemblies directory with this code...

string exeDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Directory.SetCurrentDirectory(exeDir);

Or, better yet, don't use a relative path, set p.StartInfo.WorkingDirectory to the absolute path.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...