Question

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");
Était-ce utile?

La solution

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top