C# 在文本文件中的特定位置插入文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19293040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:39:40  来源:igfitidea点击:

Insert text in a text file at specific position

c#stringtext-files

提问by jacobz

I got a text file with e.g. 3 lines:

我得到了一个文本文件,例如 3 行:

Example Text
Some text here
Text

I want to add some text directly after "here", so it will look like this:

我想在“here”之后直接添加一些文本,所以它看起来像这样:

Example Text
Some text hereADDED TEXT
Text

My code, so far, looks like this, I used some of the code from here, but it doesn't seem to work.

到目前为止,我的代码看起来像这样,我使用了这里的一些代码,但似乎不起作用。

List<string> txtLines = new List<string>();

string FilePath = @"C:\test.txt";

foreach (string s in File.ReadAllLines(FilePath))
{
    txtLines.Add(s);
}

txtLines.Insert(txtLines.IndexOf("here"), "ADDED TEXT");

using (File.Create(FilePath) { }

foreach (string str in txtLines)
{
    File.AppendAllText(FilePath, str + Environment.NewLine);
}

My problem is: txtLines.IndexOf("here")returns -1, thus throwing a System.ArgumentOutOfRangeException.

我的问题是: txtLines.IndexOf("here")返回-1,从而抛出一个System.ArgumentOutOfRangeException.

Can somebody tell me what I am doing wrong?

有人可以告诉我我做错了什么吗?

采纳答案by pingoo

Is there a reason your loading all of your text into a List? You could just update the values as you read them from the file.

您是否有理由将所有文本加载到列表中?您可以在从文件中读取值时更新这些值。

        string FilePath = @"C:\test.txt";

        var text = new StringBuilder();

        foreach (string s in File.ReadAllLines(FilePath))
        {
            text.AppendLine(s.Replace("here", "here ADDED TEXT"));
        }

        using (var file = new StreamWriter(File.Create(FilePath)))
        {
            file.Write(text.ToString());
        }

回答by Rezoan

            string filePath = "test.txt";
            string[] lines = File.ReadAllLines(FilePath);
            for (int i = 0; i < lines.Length; i++)
            {
                lines[i] = lines[i].Replace("here", "here ADDED TEXT");
            }

            File.WriteAllLines(filePath, lines);

It will do the trick that you want.

它会做你想要的把戏。

回答by ttitto

Here is a piece of code that should help you. Just replace your line txtLines.Insert(txtLines.IndexOf("here"), "ADDED TEXT"); with the below. It finds the first here and replaces it with hereADDED TEXT:

这是一段应该可以帮助您的代码。只需替换您的行 txtLines.Insert(txtLines.IndexOf("here"), "ADDED TEXT"); 与下面。它在此处找到第一个并将其替换为 hereADDED TEXT:

int indx=txtLines.FindIndex(str => str.Contains("here"));
txtLines[indx]= txtLines[indx].Replace("here", "hereADDED TEXT");