• Advertisement
Sign in to follow this  

[.net] Writing info to log file

This topic is 4209 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm using C# (.Net 1.1) to create a Windows app that's writing out to a log file, nothing complex, just a line of text stating the time that the app is run. While I've got that bit sorted out I have the problem that each time the app is accessed the stream writer appends to what's already in the file whereas I'd like it to overwrite the previous data. Anybody know the correct way to do this? Thanks

Share this post


Link to post
Share on other sites
Advertisement
You can do this a couple ways:

1. Use FileMode.Create or Truncate to create/open a file with size zero.
2. Manually truncate the stream via Stream.SetLength(0).
3. If you only want to overwrite a portion of the data, save the position at which you want to begin overwriting via Stream.Position and truncate the stream to that length via SetLength before writing any text.

Share this post


Link to post
Share on other sites
Quote:
Original post by Medhatter
I'm using C# (.Net 1.1) to create a Windows app that's writing out to a log file, nothing complex, just a line of text stating the time that the app is run. While I've got that bit sorted out I have the problem that each time the app is accessed the stream writer appends to what's already in the file whereas I'd like it to overwrite the previous data. Anybody know the correct way to do this?

Thanks


I had that problem a while ago, and the only way I could think of getting rid of the file was to just delete it, and let the StreamWriter create a new file.

Code snippet:


string theFile = "C:\\file.log";
FileInfo fileLocation = new FileInfo(theFile);
if (fileLocation.Exists)
{
Directory.Delete(theFile);
}
// Create the new file...



Good luck. =)

Share this post


Link to post
Share on other sites
Got it working now. Or should I say "for now"? Probably be back here in 5 mins but in the meantime thanks for the help.

Share this post


Link to post
Share on other sites
Although not targetting logging, Nini is a fantastic configuration library for writing INI and XML files easily.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement