Search code examples
c#iofilestream

How to read and write to file at the same time in c#


I need to use a file to make decision on binding my data. So originally I create a file contains value "NO". When first time the code read it, it will bind the data to a repeater to display, then change value in the file to "YES". When it run again (due to page reload), it read value "YES" which means data already binded, it will not bind the data again and change the file content to "NO" as original and finish running.

Here is what I tried:

// Use file to make binding data decision, 
//  avoid duplicate binding due to page reload:
using (var fileStream = 
    File.Open(Server.MapPath("~/binddecision.txt"), FileMode.Open))
{
    // read from the file
    using (var streamReader = new StreamReader(fileStream))
    {
        string line = streamReader.ReadLine();
        if (line == "NO")
        {
            companyRepeater.DataSource = companies1;
            companyRepeater.DataBind();

            LinkRepeater.DataSource = urls;
            LinkRepeater.DataBind();

            fileStream.SetLength(0); // truncate the file
            // If now is not record a loop yet, then write YES to the file
            using (var streamWriter = new StreamWriter(fileStream))
            {
                streamWriter.WriteLine("YES");
            }
        }
        else
        {
            streamReader.Close();
            // If now is a loop then write NO to the file
            using (var streamWriter = new StreamWriter(fileStream))
            {
                streamWriter.WriteLine("NO");
            }
        }
    }
}

But it still shows error about stream using conflict. I read some methods on google but fail to implement it for this algorithm.

Could any one please help me?


Solution

  • remove the line streamReader.Close(); just after else{ it should be fixed.. Anyway, if you really want to close the streamReader, you will have to open the file stream again
    fileStream = File.Open("test.txt", FileMode.Open);

    which of course you might want to let the fileStream as a local variable instead of in using.