Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing to file but file is empty

Tags:

c#

I am writing my output to this file but it keeps showing empty in the Organized.txt. If I change the last foreach loop from sr2.WriteLine and only write to the console with WriteLine then the output displays properly on console so why isn't it displaying properly in the textfile?

 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();



        }
    }
like image 485
Harmond Avatar asked Jan 13 '23 09:01

Harmond


2 Answers

You can either wrap the code in a using to ensure the stream is closed.

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

Or you can flush or close after writing.

 sr2.close();
like image 134
Reactgular Avatar answered Jan 23 '23 03:01

Reactgular


It's because you're actually writing to OrganizedVersion.txt

Looks like @Mathew is also pointing out that you haven't closed/flushed your buffer.

Try a using statement as follows:

Replace:

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

With:

using (var sr2 = new System.IO.StreamWriter("OrganizedVersion.txt"))
{
    // Your other code...
}
like image 40
Chris Pfohl Avatar answered Jan 23 '23 02:01

Chris Pfohl