class Logger

{

[FileIOPermission(SecurityAction.Assert, Unrestricted = true)]

public static void Write(Exception exException)

{

//Get the path of the executing assembly to create a log file

string logFile = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\Exceptions.log";

FileStream stream;

if (!File.Exists(logFile))

{

stream = new FileStream(logFile, FileMode.Create);

}

else

{

stream = null;

stream = new FileStream(logFile, FileMode.Append, FileAccess.Write, FileShare.Read);

}

StringBuilder sbExceptionMessage = new StringBuilder();

sbExceptionMessage.AppendLine(exException.Message);

sbExceptionMessage.AppendLine(exException.StackTrace);

sbExceptionMessage.AppendLine(Environment.NewLine);

byte[] buffer = ConvertToByteArray(sbExceptionMessage.ToString());

stream.Write(buffer, 0, buffer.Length);

stream.Close();

return;

}

/// <summary>

/// Convert the exception message to a byte array to write it to the text file as a byte stream

/// </summary>

/// <param name="val"></param>

/// <returns></returns>

private static byte[] ConvertToByteArray(string Message)

{

char[] CharArray = Message.ToCharArray();

byte[] ByteArray = new byte[CharArray.Length];

for (int i = 0; i < CharArray.Length; i++)

{

ByteArray[i] = Convert.ToByte(CharArray[i]);

}

return ByteArray;

}

}

Advertisements