2013-05-13 62 views
1

我正在将输出写入此文件,但它在Organized.txt中始终显示为空。如果我从sr2.WriteLine更改最后一个foreach循环,并且只使用WriteLine写入控制台,那么输出在控制台上正确显示,那么为什么它不能正确显示在文本文件中?写入文件但文件为空

class Program 
    { 
     public static void Main() 
     { 

      string[] arr1 = new string[200]; 


      System.IO.StreamWriter sr2 = new System.IO.StreamWriter("OrganizedVersion.txt"); 




        // Dictionary, key is number from the list and the associated value is the number of times the key is found 
        Dictionary<string, int> occurrences = new Dictionary<string, int>(); 
        // Loop test data 
        foreach (string value in File.ReadLines("newWorkSheet.txt")) 
        { 
         if (occurrences.ContainsKey(value)) // Check if we have found this key before 
         { 
          // Key exists. Add number of occurrences for this key by one 
          occurrences[value]++; 
         } 
         else 
         { 
          // This is a new key so add it. Number 1 indicates that this key has been found one time 
          occurrences.Add(value, 1); 
         } 
        } 
        // Dump result 
        foreach (string key in occurrences.Keys) 
        { 
         sr2.WriteLine(key.ToString() + occurrences[key].ToString()); 
        }    

        Console.ReadLine(); 



     } 
    } 
+0

我在代码中找不到任何'Organized.txt' – 2013-05-13 18:37:33

+6

'flush'输出缓冲区或'关闭'流。 – cgTag 2013-05-13 18:37:53

回答

5

您可以换行代码在using确保流被关闭。

 using(StreamWriter sr2 = new StreamWriter("OrganizedVersion.txt")) 
     { 
      .... 
     } 

或写入后,您可以flushclose

sr2.close(); 
+0

这是SOOOO奇怪!就在一分钟前,我在我的代码中有这样的代码,但它仍然无效,但我在代码中记录了sr2.Close(),然后保存了该文档,现在它正在工作。 – Harmond 2013-05-13 18:50:26

+0

如果您正在调试并停止调试器,则C#不会刷新缓冲区。即使你在调试时正在使用。这就是为什么如果你长时间打开流,你应该在发送任何重要数据(即写入日志文件)后刷新它们。 – cgTag 2013-05-13 18:55:40

3

这是因为你实际上OrganizedVersion.txt

貌似@Mathew还指出,你有没有关闭/清空你的缓冲区。

尝试using声明如下:

替换:

System.IO.StreamWriter sr2 = new System.IO.StreamWriter("OrganizedVersion.txt"); 

有了:

using (var sr2 = new System.IO.StreamWriter("OrganizedVersion.txt")) 
{ 
    // Your other code... 
} 
+1

我怀疑这是一个复制粘贴错误。我*希望*这是一个复制粘贴错误。 – MikeTheLiar 2013-05-13 18:39:08

+0

@mikeTheLiar我希望你是对的。如果那不是问题,我也宁愿马修得到他的信用为这个答复... – Crisfole 2013-05-13 18:41:44

+0

大声笑,没关系。我宁愿在难题上得分。 :) – cgTag 2013-05-13 18:43:17