gpt4 book ai didi

c# - 如何在不立即读取整个文件的情况下编辑文本文件

转载 作者:太空宇宙 更新时间:2023-11-03 18:24:55 25 4
gpt4 key购买 nike

我现在正在尝试解决这个问题:

编写一个程序,将文本文件中每次出现的子字符串“start”替换为“finish”。你能重写程序来只替换整个单词吗?该程序是否适用于大文件(例如 800 MB)?

我一直在尝试这样做,但显然你不能同时读写。如果有人可以查看我的代码并帮助我,那就太棒了。它抛出异常:

进程无法访问文件 'C:\Users\Nate\Documents\Visual Studio 2015\Projects\Chapter 15\Chapter 15 Question 7\Chapter 15 Question 7\TextFile.txt' 因为它正在被使用由另一个进程。

您不必直接给我答案,而是告诉我过程。谢谢!

这是我目前的代码

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace Chapter_15_Question_7
{
class Program
{
static void Main(string[] args)
{
StreamReader reader = new StreamReader(
@"C:\Users\Nate\Documents\Visual Studio 2015\Projects\Chapter 15\Chapter 15 Question 7\Chapter 15 Question 7\TextFile.txt");

StreamWriter writer = new StreamWriter(
@"C:\Users\Nate\Documents\Visual Studio 2015\Projects\Chapter 15\Chapter 15 Question 7\Chapter 15 Question 7\TextFile.txt");
using (writer)
{
using (reader)
{
string line = reader.ReadLine();
while (line != null)
{
line.Replace("start", "finish");
writer.WriteLine(line);
line = reader.ReadLine();
}
}
}
}
}

最佳答案

I've been trying to do it but apparently you cant read and write at the same time.

解决这个问题的技巧很简单:

  • 在与原始文件相同的文件夹中打开一个临时文件进行写入,
  • 逐行读取原始文件,进行替换,并将它们写入临时文件
  • 关闭原文件和临时文件
  • 复制临时文件代替原始文件

您已经在逐行读取文件,所以您需要做的就是更改 writer 以使用不同的文件名,并在循环后添加一个移动文件的调用结束了。

关于c# - 如何在不立即读取整个文件的情况下编辑文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36768631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com