4

我正在将我的输出写入这个文件,但它在 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();



        }
    }
4

2 回答 2

6

您可以将代码包装在 ausing中以确保流已关闭。

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

或者你可以flush或者close之后写。

 sr2.close();
于 2013-05-13T18:40:50.750 回答
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...
}
于 2013-05-13T18:38:29.347 回答