c# - 写入文件但文件为空

标签 c#

我正在将我的输出写入此文件,但它在 Organized.txt 中一直显示为空。如果我将最后一个 foreach 循环从 sr2.WriteLine 更改为仅使用 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();



        }
    }

最佳答案

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

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

或者你可以在写入后flush或者close

 sr2.close();

关于c# - 写入文件但文件为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16528818/

相关文章:

c# - 最好只对内部的静态字段使用类或结构

c# - 两个已知标签之间可能出现不止一次的子字符串的正则表达式

c# - fmodex 返回 ERR_FILE_BAD 在 Mono/Ubuntu 下播放 MP3 文件

c# - 在 NHibernate 中规范化 EnumStringType

c# - 如何将部分预缓存的MemoryStream与FileStream结合起来?

c# - Windows 运行时 API : MediaCapture how to limit recording file size

c# - RestSharp 打印原始请求和响应 header

c# - Log4net SmtpAppender 不工作

c# - 如何在没有具体实例的情况下使用反射获取类型的静态属性的值

C#添加程序运行不会添加完整路径