Writing to a File in a Windows Service...

S

Solomon_Man

All,
I have a Windows Service application that has database connectivity
and needs the capability to let a user know that there has been a db
failure. What is the proper way to notify a user that there has been
error within a service?

I was thinking of writing to a file and using the below code;

public void LogMessageToFile(string msg)
{
//get current directory and then prepare to create a file
name Logger.txt
string Dir = Directory.GetCurrentDirectory();
System.IO.StreamWriter sw = System.IO.File.AppendText(
Directory.GetCurrentDirectory() + "Logger.txt");


try
{
//include the time of error
string logLine = System.String.Format(
"{0:G}: {1}.", System.DateTime.Now, msg);
sw.WriteLine(logLine); //write the string to file
sw.Flush();
}
finally //clean up after myself
{
sw.Close();
}
}

Unfortunately this code does not seem to write to a file when in a
windows service. It seems to work fine in a Windows form. Any ideas or
approaches?

Thanks,
Chris
 
S

Soren S. Jorgensen

Did you check in Windows\System32 for the file ??
Default directory for services is the system dir!!

To get the dir your service exe is located in you need to do something like:
Assembly a = Assembly.GetEntryAssembly()
string exeDir = Path.GetDirectoryName(a.Location);

SSJ
 
S

Scott Roberts

Solomon_Man said:
All,
I have a Windows Service application that has database connectivity
and needs the capability to let a user know that there has been a db
failure. What is the proper way to notify a user that there has been
error within a service?

I believe the "accepted" method is to write to the Event Log.
I was thinking of writing to a file and using the below code;

public void LogMessageToFile(string msg)
{
//get current directory and then prepare to create a file
name Logger.txt
string Dir = Directory.GetCurrentDirectory();
System.IO.StreamWriter sw = System.IO.File.AppendText(
Directory.GetCurrentDirectory() + "Logger.txt");


try
{
//include the time of error
string logLine = System.String.Format(
"{0:G}: {1}.", System.DateTime.Now, msg);
sw.WriteLine(logLine); //write the string to file
sw.Flush();
}
finally //clean up after myself
{
sw.Close();
}
}

Unfortunately this code does not seem to write to a file when in a
windows service. It seems to work fine in a Windows form. Any ideas or
approaches?

Check your file/folder permissions for the account that the service is
running under (probably "Local System"). Also, when running as a service the
"Current Directory" is probably a system directory ("Windows" or
"Windows\System32") which probably isn't the best place for a log file.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top