0

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?

John
  • 5,942
  • 3
  • 42
  • 79

2 Answers2

1

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().

Mike Nakis
  • 56,297
  • 11
  • 110
  • 142
  • As a note, I am using C# with the process class from System.Diagnostics – John Jan 07 '12 at 19:46
  • Process A isnt mine so I cannot set the working directory. I need something that fixes it after the fact. In this situation, A is the task scheduler, but it can many many different applications as well so I need a different kind of solution. – John Jan 07 '12 at 19:54
  • Is Process B yours, or is your program completely separate from anything the Task Scheduler launches? – keyboardP Jan 07 '12 at 20:00
  • 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. See http://msdn.microsoft.com/en-us/library/system.io.directory.setcurrentdirectory.aspx – Mike Nakis Jan 07 '12 at 20:04
0

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.

Community
  • 1
  • 1
keyboardP
  • 68,824
  • 13
  • 156
  • 205