Because you don't have time to read everything.TM


Current Directory Of A Windows Service In .NET


 

When creating a Windows service in .NET, you may want it to read from a configuration file, or write to a log file. It seems natural that these files might be kept in whatever directory the Windows service was installed in. However, if you try to do something like this in C#:

System.Xml.XmlDocument docConfig = New System.Xml.XmlDocument(); docConfig.Load("Config.xml");

It will look for Config.xml in %WINDIR%\system32, which is almost certainly not what you want. The directory the Windows service is installed in can be accessed as System.AppDomain.CurrentDomain.BaseDirectory.

Probably the best thing to do is to set this path as the current directory. If you do it early in the OnStart method, you won't have to deal with it again. Use this code:

System.IO.Directory.SetCurrentDirectory( System.AppDomain.CurrentDomain.BaseDirectory);

Of course, setting the current working directory just tells the system how to interpret relative paths, such as "logs\\log1.txt." You can still specify absolute paths if you want, such as "C:\\Program Files\\My Service\\logs\\log1.txt." The problem is that you might not be able to make such assumptions about absolute paths when you're creating a Windows service to be deployed on other machines managed by other people.

A good compromise between hardcoding absolute paths and keeping everything in the Windows service directory is to keep a config file in the Windows service directory. The config file can specify absolute paths of other files, and can be changed by the owner of the machine it's running on.

 

StumbleUpon Stumble it!    Email Email to a friend


© 2007 - 2008 SpicePuppy.com