A simple C# class useful to save a log file on the server
The method contained in this simple example class, allows you to write a text file "log" to a folder on the server.
Code:
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
public class LogUtility
{
/// <summary>
/// Writes debug information to the log file
/// </summary>
/// <param name="log"></param>
public static void WriteLog(string log)
{
string timestampLog = DateTime.Now.ToString();
FileStream fstr = null;
StreamWriter sw = null;
try
{
// Important!
// The public folder must have write permissions
string pathLogFile = HttpContext.Current.Server.MapPath("~/public/log.txt");
fstr = File.Open(pathLogFile, FileMode.Append, FileAccess.Write);
sw = new StreamWriter(fstr);
sw.Write(timestampLog + Environment.NewLine + log + Environment.NewLine);
sw.Close();
fstr.Close();
}
catch (Exception excp)
{
sw.Close();
fstr.Close();
}
finally
{
sw.Close();
fstr.Close();
}
}
/*
Other methods of the class
*/
}
Since the class is static, the method can be called in the following way:
string debugInformation ="Houston we have a problem!";
LogUtility.WriteLog(debugInformation);