John
John

Reputation: 6268

Applications started by other processes get relative folder mixed

To put it simply, if process A starts application B. Whenever application B tries to do a relative file access such as

using(StreamReader sr = new StreamReader("log.txt"))

It accesses log.txt in the folder that process A is inside of, not the folder that application B is inside of. Right now my current fix for this is to get my application's module file name + path, remove the file name and prepend the path variable onto all my relative file access calls.

What causes this and how can I avoid it?

Upvotes: 0

Views: 409

Answers (2)

keyboardP
keyboardP

Reputation: 69372

Once you have access to the Process, you can try getting the Module. From here, you can access the full path of the process (using the FileName property) and, in turn, its directory.

string fullPath = myProcess.Modules[0].FileName;
string workingDirectory = System.IO.Directory.GetParent(fullPath);

According to this thread, 32-bit modules won't be able to enumerate modules of 64-bit assemblies, so you'll need to recompile your program to 64-bit if your target processes will be running in that mode.

Upvotes: 0

Mike Nakis
Mike Nakis

Reputation: 61984

In process A, where you launch application B, you should have specified the working folder.

Take a look at this: http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.workingdirectory.aspx

EDIT (after clarification from OP that process A is the task scheduler, and therefore cannot be modified)

I think the task scheduler allows you to specify the working directory for the application that you schedule. But in any case, even if you cannot, you can always set the current directory of your application to the right place first thing as soon as it starts, using SetCurrentDirectory().

Upvotes: 1

Related Questions