Categories

Tools

bitdefender

1&1 Web Hosting

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);
Posted in ASP.NET by MdmSoft

If our work has been of help, you can help us with a small donation...
Our programmers will thank you!



All information contained in this web site are the property of MdmSoft. The information is provided "as is", MdmSoft will not be liable for any misuse of the code contained in these pages, nor can it be for inaccuracies, grammatical errors or other factors that may have caused damage or lost earnings. MdmSoft is not responsible for the content of comments posted by users.
The examples in this area have the educational and demonstration purposes only, and may be copied only for your reference, but cannot be used for commercial purposes, or for any other purpose, without the express written consent of MdmSoft.
MdmSoft also reserves the right to change, without notice, to your liking this web site, the pages and its sections, and may suspend temporarily or definitely the various services included on this site.
While using this site, you agree to have read and accepted our Terms of Service and Privacy Policy.