我已经实现了一个基本的日志记录类,当我尝试创建它的新实例时,我得到了以下异常。
该进程无法访问文件“C:\Users\carl\Desktop\My Projects\TCV2\CallPotential.UI\bin\Debug\application.log”,因为它正被另一个进程使用。
这是记录器类的代码。
using System;
using System.IO;
using System.Reflection;
namespace CallPotential.Utilities
{
public class Logger : IDisposable
{
/// <summary>
/// Used to write output to the log file.
/// </summary>
private StreamWriter _stream;
/// <summary>
/// The absolute path to the log files location.
/// </summary>
public String LogFileName
{
get
{
// get the directory where our main assembly is located.
Assembly assembly = Assembly.GetExecutingAssembly();
String directoryName = Path.GetDirectoryName(assembly.Location);
return Path.Combine(directoryName, "application.log");
}
}
/// <summary>
/// Creates a new instance of the Logger class
/// </summary>
public Logger()
{
_stream = new StreamWriter(LogFileName);
}
/// <summary>
/// Writes a message out to the application log file.
/// </summary>
/// <param name="message">The message to write to the log file.</param>
public void Write(String message)
{
_stream.WriteLine(message);
_stream.Flush();
_stream.Close();
}
/// <summary>
/// Writes a message including the applications state to the log file.
/// </summary>
/// <param name="state">The application state at the time of the logged message.</param>
/// <param name="message">The message to be written to the log file.</param>
public void Write(AppState state, String message)
{
Write(String.Format("{0}\r\n\t{1}", state, message));
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose(bool disposing)
{
if (disposing)
{
if (_stream != null)
{
_stream.Dispose();
_stream = null;
}
}
}
~Logger()
{
Dispose(false);
}
}
}
请注意原因,但它会在构造函数中引发异常。任何帮助解决这个问题将不胜感激。