C# 修改文本文件中的特定行

C# 修改文本文件中的特定行,c#,C#,有人知道如何替换txt文件中的一行吗? 例如,我在文件中有10行,我想替换第[4]行。 我实际上有这样的代码: string old = "old string"; string nw =" new string"; int counter = 0; foreach(string s in File.ReadLines(path)) { if (s = old) { //replace the line[counter] of the text file

有人知道如何替换txt文件中的一行吗? 例如,我在文件中有10行,我想替换第[4]行。 我实际上有这样的代码:

string old = "old string";
string nw =" new string";
int counter = 0;

foreach(string s in File.ReadLines(path))
{
    if (s = old) 
    {
        //replace the line[counter] of the text file 
    } 
    counter ++;
}

我知道我可以创建一个StringCollection,并在StringCollection索引中添加每一行,只替换包含字符串的索引,以替换和覆盖文本文件,但有时可能需要大量资源


提前感谢你的帮助

重新写入整个文件会更容易:

string old = "old string";
string nw =" new string";
int counter = 0;

    Using(StreamWriter w =new StreamWriter("newfile");
    foreach(string s in File.ReadLines(path))
    {
        if (s = old) 
        {
              w. WriteLine(nw);
        }
        else
        {
              w. WriteLine(s);
        } 
        counter ++;
    }

您可以使用
StreamWriter
,将
FileStream
传递给它的构造函数。您应该能够将
文件流的位置设置为要插入新行的点

另一种方法是:

定义一些扩展方法:

static class Exts
{
public static string GetLettersAndDigits(this string source)
{
    return source.Where(char.IsLetterOrDigit)
        .Aggregate(new StringBuilder(), (acc, x) => acc.Append(x))
        .ToString();
}

public static string ReplaceWord(this string source, string word, string newWord)
{
    return String.Join(" ", source
        .Split(new string[] { " " }, StringSplitOptions.None)
        .Select(x =>
        {
            var w = x.GetLettersAndDigits();
            return w == word ? x.Replace(w, newWord) : x;
        }));
}
}
用法示例:

var input = File.ReadAllText(@"C:\test.txt");
var output = input.ReplaceWord(s, "123"); // do this inside your foreach

由于您正在逐行阅读整个内容,因此可以利用string.Replace。只需在中读取整个文件并用新文件替换旧文件:

        using (var stream = File.Open(path, FileMode.Open))
        {
            using (var reader = new StreamReader(stream))
            {
                var text = reader.ReadToEnd();
                var textReplaced = text.Replace(old, nw);
            }
        }

作为旁注,您的代码行应该说
if(s==old)
如果它是一个大文件怎么办?为什么只为了写一行就把整件事都读进去?是的,绝对不要对大文件这样做。