logwriter_dll_visualstudio/LogWriter/LogWriter.cs
Hoeglinger Eugen 7861b7861e Änderung
- DeleteLogFile löscht jetzt auch automatisch benannte Logdateien
- DeleteLogFile löscht jetzt auch Logdateien ohne Fileextension
2022-04-27 18:03:56 +02:00

635 lines
20 KiB
C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Eugen.ESystem.IO
{
/// <summary>
/// Handles a log file
/// </summary>
[Description("Handles a log file")]
public class LogWriter : Component
{
#region Version und Copyright
// Version und Copyright
static string dllName = System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase); //Den Programmnamen auslesen
static string dllVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
static object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
static string copyright = GenerateCopyright();
//Assembly Datum und Zeit
static DateTime value = AssemblyDateTime();
static string date = value.ToShortDateString();
static string time = value.ToLongTimeString();
private static DateTime AssemblyDateTime()
{
var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
var buildDateTime = new DateTime(2000, 1, 1).Add(new TimeSpan(TimeSpan.TicksPerDay * version.Build + TimeSpan.TicksPerSecond * 2 * version.Revision));
//Tage seit dem 1. Januar 2000 und Sekunden seit Mitternacht, (multiplizier mit 2 ergibt das Original)
return buildDateTime;
}
private static string CurrentYear()
{
DateTime dtn = DateTime.Now;
return dtn.Year.ToString();
}
private static string StartYear()
{
string startYear = "";
if (((AssemblyCopyrightAttribute)attributes[0]).Copyright.Contains("Copyright © "))
{
startYear = ((AssemblyCopyrightAttribute)attributes[0]).Copyright.Replace("Copyright © ", "");
while (startYear.StartsWith(" "))
{
startYear = startYear.Remove(0, 1);
}
if (startYear.Contains("-"))
{
startYear = startYear.Remove(startYear.IndexOf("-"));
}
else
{
startYear = startYear.Remove(startYear.IndexOf(" "));
}
return startYear;
}
else
{
DateTime dtn = DateTime.Now;
return dtn.Year.ToString();
}
}
private static string GenerateCopyright()
{
string startYear = StartYear();
string currentYear = CurrentYear();
if (startYear == currentYear)
{
return ((AssemblyCopyrightAttribute)attributes[0]).Copyright;
}
else
{
string temp = ((AssemblyCopyrightAttribute)attributes[0]).Copyright;
string start = temp.Remove(temp.IndexOf(startYear) - 1);
string end = (temp.Remove(0, temp.IndexOf(" by")));
return String.Concat(start, " ", startYear, "-", currentYear, end);
}
}
#endregion
#region DLL-Info
/// <summary>
/// Contains the name of the dll file.
/// </summary>
public static string DllName { private set; get; }
/// <summary>
/// Contains the version of the dll file.
/// </summary>
public static string DllVersion { private set; get; }
/// <summary>
/// Contains the copyright notice.
/// </summary>
public static string Copyright { private set; get; }
/// <summary>
/// Contains the name-, version- and copyright-information of the dll file.
/// </summary>
public static string[] DllInfo { private set; get; }
private static void SetDllInfo()
{
//Name, Version und Copyright setzen
DllName = dllName;
DllVersion = dllVersion;
Copyright = copyright;
string[] dllInfo = new string[3];
dllInfo[0] = dllName;
dllInfo[1] = dllVersion;
dllInfo[2] = copyright;
DllInfo = dllInfo;
}
protected string ProgramName { private set; get; }
protected string ProgramVersion { private set; get; }
protected string ProgramCopyright { private set; get; }
#endregion
#region enum
public enum Time
{
Write,
NoWrite
}
#endregion
#region delegates
/// <summary>
/// Provides a method, wich handles events from written messages
/// </summary>
/// <param name="sender">Sender object</param>
/// <param name="e">Event arguments</param>
[Description("Provides a method, wich handles events from written messages")]
public delegate void LogWriterEventHandler(object sender, LogWriterEventArgs e);
#endregion
#region fields
/// <summary>
/// Stores the log save path
/// </summary>
private string path = String.Empty;
/// <summary>
/// Stores the logfile name
/// </summary>
private string filename = String.Empty;
/// <summary>
/// Stores the log header
/// </summary>
private string logheader = String.Empty;
/// <summary>
/// Stores the file name format
/// </summary>
private string fileFormat = "log_{0:d}.log";
/// <summary>
/// Stores the message format
/// </summary>
private string messageFormat = "{0:T}.{1} - {2}";
#endregion
#region events
/// <summary>
/// Fired, when a message was written
/// </summary>
[Description("Fired, when a message was written")]
public event LogWriterEventHandler MessageWritten;
/// <summary>
/// Fired, when a new log file was created. Fired, when a message was written
/// </summary>
[Description("Fired, when a new log file was created. Fired, when a message was written")]
public event EventHandler FileCreated;
#endregion
#region properties
/// <summary>
/// Specifyes the log save path
/// </summary>
[Description("Specifyes the log save path")]
public string Path
{
get
{
return this.path;
}
set
{
this.path = value;
}
}
/// <summary>
/// Specifyes the file name format
/// </summary>
[Description("Specifyes the file name format")]
[DefaultValue("log_{0:d}.log")]
public string FileFormat
{
get
{
return this.fileFormat;
}
set
{
this.fileFormat = value;
}
}
/// <summary>
/// Specifyes the message format
/// </summary>
[Description("Specifyes the message format")]
[DefaultValue("{0:t}: {1}")]
public string MessageFormat
{
get
{
return this.messageFormat;
}
set
{
this.messageFormat = value;
}
}
#endregion
#region constructor
/// <summary>
/// Constructor (for DLL-Information)
/// </summary>
static LogWriter()
{
SetDllInfo();
}
/// <summary>
/// Constructor
/// </summary>
public LogWriter()
{
}
/// <summary>
/// Constructor (Filename = 'log_dd.mm.yyyy.log)
/// </summary>
/// <param name="path">Specifyes the log save path</param>
public LogWriter(string path)
{
this.path = path;
}
/// <summary>
/// Constructor (Filename = self defined)
/// </summary>
/// <param name="path">Specifyes the log save path</param>
/// <param name="filename">Specifyes the log file name</param>
public LogWriter(string path, string filename)
{
this.path = path;
this.filename = filename;
if (this.filename.EndsWith(".log"))
{
this.filename.Replace(".log", "");
}
}
#endregion
#region public members
/// <summary>
/// Writes a message
/// </summary>
/// <param name="message">Specifyes the message to be written</param>
/// <returns>Wheather the writing progress was successful</returns>
public bool WriteMessage(string message)
{
return WriteMessage(message, Time.Write);
}
/// <summary>
/// Writes a message
/// </summary>
/// <param name="message">Specifyes the message to be written</param>
/// <param name="writeTime">Indicates whether the time is written or not</param>
/// <returns>Wheather the writing progress was successful</returns>
public bool WriteMessage(string message, Time writeTime)
{
// if directory not exists, cancel
if (!Directory.Exists(this.path))
throw new DirectoryNotFoundException(AppResources.msg001);
// holds the actual date and time
DateTime time = DateTime.Now;
int ms = time.Millisecond;
string fmt = "000";
string ms3 = ms.ToString(fmt);
// creates the file name
string fileName;
if (String.IsNullOrEmpty(this.filename))
{
if (String.IsNullOrEmpty(this.path))
{
fileName = System.IO.Path.DirectorySeparatorChar.ToString();
}
else
{
fileName = this.path;
if (fileName[fileName.Length - 1] != System.IO.Path.DirectorySeparatorChar)
{
fileName += System.IO.Path.DirectorySeparatorChar;
}
}
try
{
fileName += String.Format(this.fileFormat, time);
}
catch (FormatException)
{
throw new FormatException(AppResources.msg002);
}
catch
{
return false;
}
}
else
{
if (this.path[this.path.Length - 1] != System.IO.Path.DirectorySeparatorChar)
{
if (String.IsNullOrEmpty(System.IO.Path.GetExtension(this.filename)))
{
fileName = String.Concat(path, System.IO.Path.DirectorySeparatorChar, this.filename, ".log");
}
else
{
fileName = String.Concat(path, System.IO.Path.DirectorySeparatorChar, this.filename);
}
}
else
{
if (String.IsNullOrEmpty(System.IO.Path.GetExtension(this.filename)))
{
fileName = String.Concat(this.path, this.filename, ".log");
}
else
{
fileName = String.Concat(this.path, this.filename);
}
}
}
// build message line
string line;
try
{
// creates the line
if (writeTime == Time.Write)
{
line = String.Format(this.messageFormat, new object[] { time, ms3, message });
}
else
{
line = String.Empty;
line = message;
}
}
catch (FormatException)
{
throw new FormatException(AppResources.msg002);
}
catch
{
return false;
}
try
{
StreamWriter writer;
// open file
if (!File.Exists(fileName))
{
writer = new StreamWriter(fileName);
OnFileCreated(EventArgs.Empty);
}
else
{
writer = new StreamWriter(fileName, true);
}
// write message line
writer.WriteLine(line);
// close file
writer.Close();
OnMessageWritten(new LogWriterEventArgs(time, ms, message));
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Deletes the defined log file.
/// </summary>
/// <returns>Returns 'true' if the log file does not exist or could be deleted, otherwise 'false'.</returns>
public bool DeleteLogFile()
{
try
{
if (String.IsNullOrEmpty(path))
{
return false;
}
if (String.IsNullOrEmpty(filename))
{
DateTime time = DateTime.Now;
filename = String.Concat("log_", time.ToString().Remove(time.ToString().IndexOf(" ")), ".log");
if (!File.Exists(String.Concat(Path, "\\", filename)))
{
return false;
}
}
if (!filename.EndsWith(".log"))
{
filename = String.Concat(filename, ".log");
}
if (!File.Exists(path + "\\" + filename))
{
return true;
}
else
{
File.Delete(path + "\\" + filename);
//return true;
}
if (File.Exists(path + "\\" + filename))
{
return false;
}
else
{
return true;
}
}
catch
{
return false;
}
}
private bool IsFileEmpty(string filename)
{
if (File.Exists(filename))
{
System.IO.StreamReader file = new System.IO.StreamReader(filename);
if (String.IsNullOrEmpty(file.ReadLine()))
{
file.Close();
return true; // file is empty
}
else
{
file.Close();
return false; // file is not empty
}
}
else
{
return true; // file doesn't exist - is empty
}
}
/// <summary>
/// Shows the Logfile.
/// </summary>
public void ShowLogFile()
{
//string messageText = "";
//string messageHeadline = "";
//string file = String.Concat(tempDir, "\\CleanUp.log");
if (File.Exists(String.Concat(path, "\\", filename)))
{
// Log-Datei anzeigen
try
{
Process P = new Process();
P.StartInfo.FileName = "Notepad.exe";
// hier kann z.B. eine Textdatei mit übergeben werden
P.StartInfo.Arguments = String.Concat(path, "\\", filename);
P.Start();
}
catch
{
// Editor nicht gefunden
MessageBox.Show(AppResources.msg003,
AppResources.msg001cap,
MessageBoxButtons.OK,
MessageBoxIcon.Error,
MessageBoxDefaultButton.Button1);
}
}
else
{
// Log-Datei nicht gefunden
MessageBox.Show(AppResources.msg004,
AppResources.msg002cap,
MessageBoxButtons.OK,
MessageBoxIcon.Warning,
MessageBoxDefaultButton.Button1);
}
}
#endregion
#region protected members
/// <summary>
/// Fires the MessageWritten event
/// </summary>
/// <param name="e"></param>
protected void OnMessageWritten(LogWriterEventArgs e)
{
if (MessageWritten != null)
MessageWritten(this, e);
}
/// <summary>
/// Fires the FileCreated event
/// </summary>
/// <param name="e"></param>
protected void OnFileCreated(EventArgs e)
{
if (FileCreated != null)
FileCreated(this, e);
}
#endregion
}
#region LogWriterEventArgs class
/// <summary>
/// LogWriterEventArgs stores information about the sent log message
/// </summary>
public class LogWriterEventArgs : EventArgs
{
#region fields
/// <summary>
/// Stores the message post time
/// </summary>
private DateTime time;
/// <summary>
/// Stores the milliseconds of the post time of the message
/// </summary>
private int millisecond;
/// <summary>
/// Stores the message
/// </summary>
private string message;
#endregion
#region properties
/// <summary>
/// Specifyes the message post time
/// </summary>
[Description("Specifyes the message post time")]
public DateTime Time
{
get
{
return this.time;
}
}
/// <summary>
/// Specifyes the message
/// </summary>
[Description("Specifyes the message")]
public string Message
{
get
{
return this.message;
}
}
#endregion
#region constructor
/// <summary>
/// Constructor
/// </summary>
/// <param name="time">Specifyes the message post time</param>
/// <param name="millisecond">Specifyes the message post milliseconds</param>
/// <param name="message">Specifyes the message</param>
public LogWriterEventArgs(DateTime time, int millisecond, string message)
: base()
{
this.time = time;
this.millisecond = millisecond;
this.message = message;
}
#endregion
}
#endregion
}