Search code examples
c#.netwinformsfilestreamreader

Accessing and changing a txt document while running a windows form in C#


I'm currently teaching myself how to use the Windows Form to interact with an MIRC bot I've also been making. Currently, I have question coming in through the bot and put out to a .txt file, which is then being picked up by the Windows Form. Currently, my code is working when it pulls the data, but once I create the StreamReader to pull from the text, MIRC becomes unable to modify the file any further while the Windows Form is running. I've tried putting in Close(), but that didn't do the trick. here is the code I'm using for the button in Windows Form:

private void button1_Click(object sender, EventArgs e)
{
    i = 0;
    questionDoc = new StreamReader("questions.txt");
    if (questionDoc.ReadLine() != null)
    {
        fullText = questionDoc.ReadToEnd();
        questionList = fullText.Split('\t');
        for (int j = 0; j < questionList.Length; j++)
        {
            this.label1.Text = questionList[j];
        }
        questionDoc.Close();
    }
    else
        this.label1.Text = "No questions!";
}

So currently I can pull the questions, but the txt document can no longer be updated the first time I click that button. Is there another way around this? Thanks for your help!


Solution

  • You can change the file access using File.Open() so that other processes can read and write to it using FileShare.ReadWrite (MSDN):

    using (FileStream fs = File.Open("questions.txt", FileMode.Open,
           FileAccess.Read, FileShare.ReadWrite)) {
        using (StreamReader questionDoc = new StreamReader(fs)) {
            // do your stuff
        }
    }