2017-11-11 39 views
0

背景: 我正在使用控制台应用程序,将每行保存到指定的日志文件(例如2017年1月5日为01_05_2017_log_.txt)List.Add()重新添加以前的值

每个日志都按其设定的方式添加,但是我似乎无法弄清楚的问题是为什么它会再次添加包含日志值的列表的所有以前的值。

因此,当调用CurrentLogs.Add("Some log here")时,它会将Some log here添加到CurrentLogs列表中。

让我们再次调用它,但这次使用的字符串是another log here。在列表中的项目如下:

  • 这里
  • 这里
  • 一些记录一些日志这里另一个日志

,然后将这些3重新添加,如果我尝试使用.Add方法再次

我看了看周围的方式,谷歌,无济于事。

// This is the List object I'm using. 
public class LoggerList<T> : List<T> 
{ 
    public event EventHandler OnAdd; 
    public new void Add(T item) 
    { 
     OnAdd?.Invoke(this, null); 
     base.Add(item); 
    } 
} 

现在这里是Logger类,其中Logger.CurrentLogs.Add()被称为f光盘

public class Logger 
{ 
    // Directory in which logs are stored 
    private static string _loggerPath = "Logs/"; 
    // Used to check if the Old Logs have already been added to the OldLogs Object 
    private static bool _alreadyPulled = false; 
    // Previously saved logs before the current use of the console app 
    private static readonly List<string> OldLogs = new List<string>(); 
    // Current logs to be added here 
    public static LoggerList<string> CurrentLogs = new LoggerList<string>(); 

    //EventHandler to Save Logs on add 
    public static void OnAdd(object sender, EventArgs e) 
    { 
     SaveLog(); 
    } 

    /// <summary> 
    /// Saves the logs 
    /// </summary> 
    public static void SaveLog() 
    { 
     if (!Directory.Exists(_loggerPath)) 
     { 
      Directory.CreateDirectory(_loggerPath); 
     } 

     string fileName = _loggerPath + DateTime.Now.ToString("MM_dd_yyyy") + "_log_.txt"; 
     // If the File Exists, contiue with loading 
     if (File.Exists(fileName)) 
     { 
      // If the OldLogs have not already been pulled, pull them 
      if (!_alreadyPulled) 
      { 
       var oldLogs = File.ReadAllLines(fileName).ToList(); 
       foreach (var i in oldLogs) 
       { 
        OldLogs.Add(i); 
       } 
       _alreadyPulled = true; // Let know that the OldLogs have already been pulled this instance 
      } 
      List<string> lines = OldLogs; 
      lines.AddRange(CurrentLogs); 
      File.Delete(fileName); 

      var sr = File.CreateText(fileName); 
      foreach (string x in lines) 
      { 
       sr.WriteLine(x); 
      } 
      sr.Flush(); 
      sr.Close(); 
     } 
     // Only go here if the file doesn't exist 
     else 
     { 
      var sr = File.CreateText(fileName); 
      foreach (string x in CurrentLogs) 
      { 
       sr.WriteLine(x); 
      } 
      sr.Flush(); 
      sr.Close(); 
     } 
    } 
} 

这里是Program.cs(添加此因为这是信使类被称为 类节目 { 静态无效的主要(string [] args) Logger.CurrentLogs.OnAdd + = Logger.OnAdd; CommandManager.InitCommands(); CheckForEntrie S();

} 

    private static void CheckForEntries() 
    { 
     while (true) 
     { 
      Console.ForegroundColor = ConsoleColor.White; 
      var text = Console.ReadLine(); 
      try 
      { 
       if (!SendEntry(text)) 
       { 
        Console.WriteLine("Failed to send"); 
       } 
      } 
      catch (CommandNotFoundException ex) 
      { 
       Messenger.Send("Commmand does not exist (" + text.GetWords()[0] + ")"); 
      } 
     } 
    } 

    private static bool SendEntry(string text) 
    { 
     try 
     { 
      if (text.FirstCharacter() != "/") 
      { 
       return false; 
      } 
      else 
      { 
       string text2 = text.Substring(1); 
       string commandname = text2.GetWords()[0]; 
       foreach (Command c in CommandManager.RegisteredCommands) 
       { 
        if (c.Name.ToLower() == commandname.ToLower()) 
        { 
         c.Run(text2.Substring(commandname.Length)); 
         return true; 
        } 
        else 
        { 
         foreach (string alias in c.Aliases) 
         { 
          if (alias.ToLower() == commandname.ToLower()) 
          { 
           c.Run(text2.Substring(commandname.Length + 1)); 
           return true; 
          } 
         } 
        } 
       } 
       throw new CommandNotFoundException(); 
      } 
     } 
     catch (CommandNotFoundException ex) 
     { 
      throw ex; // Placed here so that the catch (Exception) does not go beyond 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex); 
      return false; 
     } 
    } 


} 

这里是Messenger.cs(凡。新增直接发生)

// Color codes 
private static readonly string[] codes = 
    { 
     "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", 
     "a", "b", "c", "d", "e", "f" 
    }; 

    private static string Format(string rawText) 
    { 
     return "&e" + TimeStamp() + " " + rawText; 
    } 

    public static string TimeStamp() 
    { 
     return "<" + DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss") + ">"; 
    } 
    public static void Send(string textRaw) 
    { 
     Logger.CurrentLogs.Add(Format(textRaw).Substring(2)); 
     string text = Format(textRaw); 
     List<int> skipOver = new List<int>(); 
     for (int txt = 0; txt <= text.Length - 1; txt++) 
     { 
      char[] chars = text.ToCharArray(); 
      if (chars[txt].ToString() == "&") 
      { 
       List<string> hi = codes.ToList(); 
       if (hi.Contains(chars[txt + 1].ToString().ToLower())) 
       { 
        skipOver.Add(txt); 
        skipOver.Add(txt + 1); 
       } 
      } 
     } 

     for (int x = 0; x <= text.Length - 1; x++) 
     { 

      char[] chars = text.ToCharArray(); 
      if (chars[x] == "&".ToCharArray()[0]) continue; 
      if (x <= 1 || skipOver.Contains(x)) continue; 
      char behind2 = chars[x - 2]; 
      char behind1 = chars[x - 1]; 
      if (behind2.ToString() == "&") 
      { 
       bool isGoodCode = false; 
       foreach (string s in codes) 
       { 
        if (s.ToLower() == behind1.ToString().ToLower()) 
        { 
         isGoodCode = true; 
        } 
       } 

       if (isGoodCode) 
       { 
        skipOver.Add(x - 2); 
        skipOver.Add(x - 1); 
        if (x < text.Length - 1) 
        { 
         Color baseColor = ToColor(behind1.ToString()); 
         ConsoleColor cColor = ToConsoleColor(baseColor); 
         Console.ForegroundColor = cColor; 
         Console.Write(chars[x]); 
        } 
        else if (x == text.Length - 1) 
        { 
         Color baseColor = ToColor(behind1.ToString()); 
         ConsoleColor cColor = ToConsoleColor(baseColor); 
         Console.ForegroundColor = cColor; 
         Console.WriteLine(chars[x]); 
        } 
       } 
       else 
       { 
        if (x < text.Length - 1) 
        { 
         Console.Write(chars[x - 2]); 
         Console.Write(chars[x - 1]); 
         Console.Write(chars[x]); 
        } 
        else if (x == text.Length - 1) 
        { 
         Console.Write(chars[x - 2]); 
         Console.Write(chars[x - 1]); 
         Console.WriteLine(chars[x]); 
        } 
       } 
      } 
      else 
      { 
       if (x < text.Length - 1) 
       { 
        Console.Write(chars[x]); 
       } 
       else if (x == text.Length - 1) 
       { 
        Console.WriteLine(chars[x]); 
       } 
      } 
     } 
    } 
+0

凡不添加发生的呢?也许问题出在那里...... – casiosmu

+0

只有两个注意事项: 1.列表内容刷新到文件后,不应该清除CurrentLogs? 2.您不觉得这会更简单吗?使用 File.AppendAllLines(fileName,CurrentLogs); 而不是像当前实现加载/重写现有的日志文件吗? 我相信会省掉很多代码。至少这就是我在我的项目中使用的简单记录器中所做的。 –

回答

2

在这些线路

List<string> lines = OldLogs; 
lines.AddRange(CurrentLogs); 

“线” 指向同一个对象 “oldlogs中”。因此,您不断添加条目到同一个列表。

你可以尝试,而不是复制:

var lines = new List<string>(OldLogs); 
+0

有趣的是,它的工作。 – apotter96

相关问题