-3

I've been trying to figure out what's my error here for a few minutes now. can someone help?

        public void UpdateItemList(string word, string replacement)
        {
            StreamReader reader = new StreamReader("items.txt");
            string input = reader.ReadToEnd();
            using (StreamWriter writer = new StreamWriter("items.txt", true))
            {
                {
                    string output = input.Replace(word, replacement);
                    writer.Write(output);
                }
                writer.Close();
            }
            reader.Close();
        }

code error

I added reader.Close() and writer.Close() and gave different orientation, I'm not sure what I'm missing.

tin
  • 15
  • 2
  • 6
    What if you dispose `reader` before using `writer`? – derekbaker783 Feb 18 '23 at 15:51
  • See also: [this answer](https://stackoverflow.com/questions/26741191/ioexception-the-process-cannot-access-the-file-file-path-because-it-is-being#answer-72783342). – derekbaker783 Feb 18 '23 at 15:54
  • To restate the first comment, your reader and writer streams refer to the same file. But you don't close the reader stream until _after_ you attempt to write to the file. – Eric J. Feb 18 '23 at 16:01
  • There's no point calling `Close` when you create the object with a `using` statement, which is why you should be doing the same for `StreamReader`. You need to strive for consistency in your code. Why use a `using` statement for one and not the other? – jmcilhinney Feb 18 '23 at 16:15
  • 1
    There's no point even using a `StreamReader` and `StreamWriter` anyway. You should just call `File.ReadAllText` and `File.WriteAllText`. They will do all the opening and closing for you. – jmcilhinney Feb 18 '23 at 16:17
  • It is always a good programming practice to write methods that will check if the file being accessed by your program is being used by another process already and then end that process. You could define a boolean method that returns true if the file is being used by another process then inside that put code block to end that process else continue with the rest of the execution. –  Feb 18 '23 at 17:22

1 Answers1

2

you should close StreamReader before opening streamWriter

public void UpdateItemList(string word, string replacement)
{
    string input;
    using (StreamReader reader = new StreamReader("items.txt"))
    {
         input = reader.ReadToEnd();
     }

    using (StreamWriter writer = new StreamWriter("items.txt", false))
    {
        string output = input.Replace(word, replacement);
        writer.Write(output);
    }
}
Hamid Mohammadi
  • 286
  • 1
  • 10