【问题标题】:How to close file that has been read如何关闭已读取的文件
【发布时间】:2014-04-25 14:51:41
【问题描述】:

所以我试图关闭一个已经打开的文件(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);
            }

【问题讨论】:

  • 为什么要从同一个文件(File.ReadLines("transactions.txt")File.ReadAllText("transactions.txt"))读取多次?
  • 因为我需要从中提取信息。我从文件中获取事务,在文本框中对其进行编辑,然后将其保存回文件中。

标签: c# streamreader streamwriter


【解决方案1】:

这里的问题是File.ReadLines 在您读取文件时保持文件打开,因为您已经将向其写入新文本的调用在循环中,文件仍然是打开的。

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

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

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

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

【讨论】:

    【解决方案2】:

    using 语句中直接使用StreamReader,例如:

    var lines = new List<string>();
    
    using (StreamReader reader = new StreamReader(@"C:\test.txt")) {
        var line = reader.ReadLine();
    
        while (line != null) {
            lines.Add(line);
            line = reader.ReadLine();
        }
    }
    

    通过使用using 语句,StreamReader 实例将在完成后自动被丢弃。

    【讨论】:

      【解决方案3】:

      你可以试试这个:

      File.WriteAllLines(
          "transactions.txt",
          File.ReadAllLines("transactions.txt")
              .Select(x => x.Contains(ID) ? textBox2.Text : x));
      

      它工作正常,但如果文件很大,你必须找到其他解决方案。

      【讨论】:

        【解决方案4】:

        您可以使用 StreamReader 类代替 File 类的方法。通过这种方式,您可以使用 Stream.Close() 和 Stream.Dispose()。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-03-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-01-02
          相关资源
          最近更新 更多