Search code examples
c#streamreaderstreamwriter

C# StreamWriter won't work after calling StreamReader


I'm trying to make betting program in C#, storing the user's data in a txt file. I have no problem reading the data from it. However, I can't manage to overwrite it.

From what I've tested, if I call the StreamWriter part alone the overwriting happens just fine. When I put the same code after the StreamReader part, the code will reach the Console.WriteLine("reached"); line and ignore everything after it (username is never written in the console). No error is detected and compilation won't stop either.

Here's the class code:

    class Dinero
    {
            private List<string> data;
            private string path = @"C:\Users\yy\Documents\Visual Studio 2015\Projects\ErikaBot\ErikaBot\img\bank_data.txt";

           ...
           some other methods here
           ...

            public void thing(string username, int money)
            {
                FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
                data = new List<string>();
                using (StreamReader sr = new StreamReader(fs))
                {
                    string a = sr.ReadLine();
                    for (int i = 0; a != null; i++)
                    {
                        if (a != username)
                        {
                            data.Add(a);
                        }
                        else i++;
                        a = sr.ReadLine();
                    }
                }

                string b = Convert.ToString(money);
                Console.WriteLine("reached");
                using (StreamWriter tw = new StreamWriter(fs))
                {
                    Console.WriteLine(username);
                    if (data != null)
                    {
                        for (int i = 0; i < data.Count; i++)
                        {
                            tw.WriteLine(data.ElementAt(i));
                        }
                    }
                    string money2 = Convert.ToString(money);
                    tw.WriteLine(username);
                    tw.WriteLine(money2);
                }
            }
        }

Solution

  • By disposing StreamReader you also dispose the FileStream. Either repeat the filestream initialisation before the using statement for StreamWriter or put the latter in the using statement for StreamReader.