Skip to content

Instantly share code, notes, and snippets.

@mabuenox
Created February 28, 2013 07:28
Show Gist options
  • Save mabuenox/5054939 to your computer and use it in GitHub Desktop.
Save mabuenox/5054939 to your computer and use it in GitHub Desktop.
Write Log on Windows Service. Only a guide, this code can be enhanced.
private void EscribirLog(string message)
{
try
{
DirectoryInfo dirInfo = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "\\Log");
if (!dirInfo.Exists)
{
dirInfo.Create();
}
FileInfo[] files = dirInfo.GetFiles();
foreach (FileInfo file in files)
{
if (file.LastWriteTime < DateTime.Today.AddDays(-7))
{
file.IsReadOnly = false;
file.Delete();
}
}
}
catch (Exception)
{
}
finally
{
string nombreFichero = DateTime.Today.ToShortDateString();
nombreFichero = nombreFichero.Replace("/", "-");
// Append new text to an existing file
using (System.IO.StreamWriter file = new System.IO.StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\Log" + "\\" + nombreFichero + ".txt", true))
{
file.WriteLine(DateTime.Now.ToString() + " " + message);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment