Voici la solution que j'ai trouvé
Classe de base :
public sealed class Log
{
#region Déclarations et propriétés
private string logFilePath;
/// <summary>
/// Path to save the file
/// </summary>
public string LogFilePath
{
get
{
return logFilePath;
}
set
{
logFilePath = value;
}
}
//Contructeur
public Log()
{
}
public void Add(object stringToAdd)
{
try
{
if (LogFilePath != "")
{ //verify if the directory and file exist
FileInfo file = new FileInfo(LogFilePath);
if (!file.Directory.Exists) file.Directory.Create();
StreamWriter stream = null;
if (!file.Exists)
stream = file.CreateText();
else
stream = file.AppendText();
try
{
stream.Write(stringToAdd.ToString()); // empty line;
}
catch (Exception)
{
}
finally
{
try
{
stream.Close();
}
catch (Exception)
{
}
finally
{
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
#endregion //Fonctions Publiques
Classe qui ajoute les erreurs dans unfichier Log
public class ExceptionLog
{
protected static Log log = new Log();
public static string LogFilePath
{
get
{
return log.LogFilePath;
}
set
{
log.LogFilePath = value;
}
}
public static void Add(Exception ex, bool exceptionAllreadyManaged = false)
{
StringBuilder exceptionString = new StringBuilder();
exceptionString.AppendLine(); // empty line;
try
{
exceptionString.AppendLine(System.Windows.Forms.Application.ProductName + " Version : " + System.Windows.Forms.Application.ProductVersion);
}
catch (Exception)
{
exceptionString.AppendLine("Exception by getting production name and version");
}
if (exceptionAllreadyManaged)
exceptionString.Append("Erreur gérée (ajout pour suivi : ");
else
exceptionString.Append("Erreur non gérée : ");
exceptionString.AppendLine("Exception : " + ex.ToString());
exceptionString.AppendLine(DateTime.Now.ToString());
exceptionString.AppendLine(Utils.StringFromException(ex));
log.Add(exceptionString.ToString());
#if DEBUG
if (!exceptionAllreadyManaged)
Utils.ReportError(ex);
#endif
}
}
Classe pour autre Log
class LogForData
{
protected static Log log = new Log();
public static string LogFilePath
{
get
{
return log.LogFilePath;
}
set
{
log.LogFilePath = value;
}
}
private static bool headerAdded = false;
private static void addData(DateTime date, string data1)
{
StringBuilder strBuidler = new StringBuilder();
strBuidler.Append(date.ToString("dd/MM/yy HH:mm:ss"));
strBuidler.Append(";");
strBuidler.Append(data1);
strBuidler.AppendLine();
log.Add(strBuidler.ToString());
}
public static void Add(DateTime date, string data1)
{
// Add Header
if (!headerAdded)
{
log.Add("Date; Data1 \r\n");
headerAdded = true;
}
addData( date, data1);
}
J'espère que cette solution pourra servir à d'autres.
Vincnet68