-1

I have a program that has been running as a scheduled task for quite some time. I made one change to it, not even related to the TextReader and placed a copy of the .exe back on the server (Server 2003 R2 SP2) and now when you run the program from Scheduled Tasks or just by double clicking on the .exe the following line tries to read the file IPAddressMonitor.ini from C:\Documents and Settings\user\ instead of in the folder the .exe is in C:\IPAddressMonitor. Any idea why?

TextReader tr = new StreamReader("IPAddressMonitor.ini");
John Wesley Gordon
  • 910
  • 2
  • 17
  • 39
  • 1
    Are you doing something (manually or via coding) that could change the current working directory? – Steve May 02 '14 at 20:03
  • Not through coding. What you see is what I am running. Am I misunderstanding that the directory the .exe is executed from should be where it pulls the .ini from? – John Wesley Gordon May 02 '14 at 20:06
  • Don't know why that is happening, but you could always just use reflection to get the path to the .exe - then as long as your .ini is in the same folder as the executable (or somehwere relative to it) you won't run into this problem anymore – rwisch45 May 02 '14 at 20:07
  • What sets the "current directory?" I thought it was from the directory the .exe was executed from. Is this not correct? – John Wesley Gordon May 02 '14 at 20:10
  • Did you set the Path in the Task scheduler for your program? – Steve May 02 '14 at 20:16
  • Yes. The Path in Task Scheduler is set to C:\IPAddressMonitor. Getting the same response executing by double clicking the .exe though. – John Wesley Gordon May 02 '14 at 20:18
  • @rwisch45 Could you post an example or link to this method of reflection? I do have my .ini always in the same path as the .exe – John Wesley Gordon May 02 '14 at 20:20

1 Answers1

1

Use reflection to get the path to your executable - then as long as your .ini is in the same folder as the executable (or somehwere relative to it) you won't run into this problem anymore:

static public string AssemblyDirectory
{
    get
    {
        string codeBase = Assembly.GetExecutingAssembly().CodeBase;
        UriBuilder uri = new UriBuilder(codeBase);
        string path = Uri.UnescapeDataString(uri.Path);
        return Path.GetDirectoryName(path);
    }
}

or

Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)

See this SO post for more info

Community
  • 1
  • 1
rwisch45
  • 3,692
  • 2
  • 25
  • 36