我现在正试图解决这个问题:
编写一个程序来替换每个子串的出现" start"用"完成"在文本文件中。你能改写程序只替换整个单词吗?该程序是否适用于大文件(例如800 MB)?
我一直试图这样做,但显然你不能同时读写。 如果有人可以查看我的代码并帮助我,那就太棒了。它抛出异常:
The process cannot access the file 'C:\Users\Nate\Documents\Visual Studio 2015\Projects\Chapter 15\Chapter 15 Question 7\Chapter 15 Question 7\TextFile.txt' because it is being used by another process.
你不必直接给我答案,而是告诉我这个过程。谢谢!
此处是我的代码
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();
}
}
}
}
}
}
答案 0 :(得分:5)
我一直试图这样做,但显然你不能同时读写。
解决这个问题的诀窍很简单:
您已经在逐行阅读文件,所以您需要做的就是更改writer
以使用不同的文件名,并在循环结束后添加调用以移动文件。
答案 1 :(得分:3)
尚未测试过。但这来自我在评论中发布的链接。
我要做的是制作临时文件并逐行编写,然后用新文件替换旧文本文件。
这样的事情:
string path = @"C:\Users\Nate\Documents\Visual Studio 2015\Projects\Chapter 15\Chapter 15 Question 7\Chapter 15 Question 7\TextFile.txt";
string pathTmp = @"C:\Users\Nate\Documents\Visual Studio 2015\Projects\Chapter 15\Chapter 15 Question 7\Chapter 15 Question 7\TextFile-tmp.txt";
using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (StreamReader sr = new StreamReader(fs))
{
string line;
while ((line = sr.ReadLine()) != null)
{
using (StreamWriter writer = new StreamWriter(pathTmp))
{
writer.WriteLine(line.Replace("start", "finish"));
}
}
}
}
File.Delete(path);
File.Move(pathTmp, path);
答案 2 :(得分:0)
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)
{
string myNewLine=line.Replace("start", "finish");
writer.WriteLine(myNewLine);
}
}
}
}
}
答案 3 :(得分:0)
我认为这将是一种更简洁的方法:
string fileToUpdate = @"C:\Users\Nate\Documents\Visual Studio 2015\Projects\Chapter 15\Chapter 15 Question 7\Chapter 15 Question 7\TextFile.txt";
string tempFile = fileToUpdate + ".tmp";
File.WriteAllLines(tempFile,
File.ReadLines(fileToUpdate)
.Select(line => line.Replace("start", "finish")));
File.Delete(fileToUpdate);
File.Move(tempFile, fileToUpdate);