ErrorMessageWriter<T>
Class that is specialized in writing error messages to the error message file.
using System;
using System.IO;
using System.Text;
namespace Relativity.DataExchange.Io
{
public sealed class ErrorMessageWriter<T> : IDisposable where T : IErrorArguments
{
private readonly object lockObject = new object();
private Lazy<StreamWriter> stream;
private bool disposed;
public string FilePath { get; }
public bool FileCreated { get; set; }
public ErrorMessageWriter(string filePath)
{
lock (lockObject) {
if (string.IsNullOrEmpty(filePath))
filePath = TempFileBuilder.TemporaryFileNameWithoutCreatingEmptyFile("rel-errors");
FilePath = filePath;
SetStreamToInitialValue(filePath);
}
}
public ErrorMessageWriter()
: this(string.Empty)
{
}
public void Dispose()
{
lock (lockObject) {
if (!disposed && stream.IsValueCreated) {
stream.Value?.Dispose();
disposed = true;
}
}
}
public void WriteErrorMessage(T toWrite)
{
lock (lockObject) {
string value = toWrite.FormattedLineInFile();
stream.Value.WriteLine(value);
stream.Value.Flush();
}
}
internal void ReleaseLock()
{
lock (lockObject) {
Dispose();
SetStreamToInitialValue(FilePath);
disposed = false;
}
}
private void SetStreamToInitialValue(string filePath)
{
stream = new Lazy<StreamWriter>(delegate {
FileCreated = true;
return new StreamWriter(filePath, true, Encoding.Default);
});
}
}
}