如何关闭已读取的文件

Zin*_*ium 0 c# streamwriter streamreader

所以我试图关闭一个已经打开的文件(transactions.txt),我曾经将其读入文本框,现在我想保存回该文件,但是问题调试表明该文件正在使用中,所以我需要找到一种关闭它的方法。谁能帮我这个?谢谢!

        SearchID = textBox1.Text;
        string ID = SearchID.ToString();
        bool idFound = false;
        int count = 0;

        foreach (var line in File.ReadLines("transactions.txt"))
        {

            //listView1.Items.Add(line);

            if (line.Contains(ID))
            {
                idFound = true;
            }

            //Displays Transactions if the variable SearchID is found.
            if (idFound && count < 8)
            {
                textBox2.Text += line + "\r\n";
                count++;

            }
        }
    }

    private void SaveEditedTransaction()
    {
        SearchID = textBox1.Text;
        string ID = SearchID.ToString();
        bool idFound = false;
        int count = 0;

        foreach (var lines in File.ReadLines("transactions.txt"))
        {

            //listView1.Items.Add(line);

            if (lines.Contains(ID))
            {
                idFound = true;
            }

            if (idFound)
            {
                string edited = File.ReadAllText("transactions.txt");
                edited = edited.Replace(lines, textBox2.Text);
                File.WriteAllText("Transactions.txt", edited);
            }
Run Code Online (Sandbox Code Playgroud)

ang*_*son 5

这里的问题是File.ReadLines在读取文件时使文件保持打开状态,因为您已在循环发出了向其写入新文本的调用,因此文件仍处于打开状态。

相反,当您找到id时,我会简单地跳出循环,然后将写入文件的if语句放在循环外。

但是,这意味着您还需要维护要替换的行。

因此,实际上,我改为使用File.ReadAllLines。在循环开始之前,这会将整个文件读入内存并关闭它。

现在,务实的人可能会争辩说,如果该文本文件中有很多文本,File.ReadLines(当前使用的)内存将比File.ReadAllLines(我建议您使用的)更少的内存使用,但是如果是这样的话,那么您应该切换到数据库,该数据库无论如何仍将更适合您的目的。但是,对于该文件中有5行的玩具项目来说,这有点过头了。