2015-04-07 31 views
1

我有写入列表到txt文件的问题。如果我运行我的Save方法,它只会生成空白的txt文件。我从txt文件填充这个列表,它工作正常,所以我确定它不是空的(我可以在日历中看到我的约会)。有我的方法。C# - 无法写入列表到txt文件

编辑

好吧,我知道问题在哪里。 Load中的_appointments列表与Save中的_appointments列表不同。我不知道为什么。我没有任何其他名单。这是同样的,但它不是:/

public bool Load() 
    { 
     DateTime start = new DateTime(2000,01,01); 
     CultureInfo enUS = new CultureInfo("en-US"); 
     int length = 0; 
     string screenDiscription = ""; 
     bool occursOnDate = false; 
     string line; 
     int i = 1; 
     StreamReader sr = new StreamReader("appointments.txt"); 

     if (!File.Exists("appointments.txt")) 
     { 
      return false; 
     } 

     while ((line = sr.ReadLine()) != null) 
     { 
      if (i % 4 == 1) 
      { 
       start = DateTime.ParseExact(line, "ddMMyyyy HHmm", enUS); 
      } 
      if (i % 4 == 2) 
      { 
       length = int.Parse(line); 
      } 
      if (i % 4 == 3) 
      { 
       screenDiscription = line; 
      } 
      if (i % 4 == 0) 
      { 
       Appointment appointment = new Appointment(start, length, screenDiscription, occursOnDate); 
       _appointments.Add(appointment); 
      } 
      i++; 
     } 
     sr.Close(); 
     return true; 
    } 

    public bool Save() 
    { 
     StreamWriter sw = new StreamWriter("appointments.txt"); 

     if (File.Exists("appointments.txt")) 
     { 
      foreach(IAppointment item in _appointments) 
      { 
        sw.WriteLine(item.Start); 
        sw.WriteLine(item.Length); 
        sw.WriteLine(item.DisplayableDescription); 
        sw.WriteLine(" "); 
      } 
      sw.Close(); 
      return true; 
     } 
     else 
     { 
      File.Create("appointments.txt"); 

      foreach (IAppointment item in _appointments) 
      { 
        sw.WriteLine(item.Start); 
        sw.WriteLine(item.Length); 
        sw.WriteLine(item.DisplayableDescription); 
        sw.WriteLine(" "); 
      } 
      sw.Close(); 
      return true; 
     } 
    } 
+0

您是否尝试过创建'TextWriter'而不是'StreamWriter'?使用TextWritier的 – iamawebgeek

+0

会使您受益更多。 – BIW

+0

@BradleyWilson我以为'StreamWriter'可以与字节一起工作,不是吗? – iamawebgeek

回答

0

我已经重构你的Save方法,但我无法测试它,因为我没有你IAppointmentAppointment

public void Save() 
{ 
    var builder = new StringBuilder() 
    foreach (IAppointment item in _appointments) 
    { 
     builder.AppendLine(item.Start); 
     builder.AppendLine(item.Length); 
     builder.AppendLine(item.DisplayableDescription); 
     builder.AppendLine(" "); 
    } 

    File.WriteAllText("appointments.txt", builder.ToString()); 
} 

请注意以下几点:我认为您的bool返回类型是多余的,因为该方法始终在所有代码路径上返回true;因此我已将其更改为void。另外,我正在使用StringBuilder来构建文件内容,然后使用内置的File.WriteAllText方法来抽象出您通常不得不用于打开流,流写入器,关闭等的IO操作。

我不确定这是否能解决您的问题,因为正如我所说,我无法测试它,而且我不确定您的代码究竟有什么问题,但至少它可能是更清洁,更容易处理。

+0

谢谢你的回应。我的保存方法必须是bool,因为我的保证需要它。我调试了它,并且_appointments列表出现问题。它是空的。我不知道为什么,因为我从文件加载它,我可以在我的日历中使用它,但是当我想将它写入文件时,它是空的。 – Laguland

+0

“我的保存方法必须是bool,因为我的保密要求它”,如果它总是返回true我真的不知道该说些什么! – BenjaminPaul