【问题标题】:read file and write text when find the line找到行时读取文件并写入文本
【发布时间】:2014-11-17 12:58:52
【问题描述】:

我有一个包含很多行的文件。我逐行阅读并找到一个特定的字符串,我需要在此之后插入另一行。

谷歌-源文件 脸书

google - 我应该得到的文件 堆栈溢出 脸书

using (var fs = File.Open(fileOutPath, FileMode.OpenOrCreate))
        {
                using (StreamReader sr = new StreamReader(fs))
                {
                    while ((line = sr.ReadLine()) != null)
                    {
                        if (line.StartsWith("google"))
                        {

我应该怎么做才能在下面的行中写“stasckoverflow”

【问题讨论】:

    标签: c# visual-studio-2010 file filestream


    【解决方案1】:

    您不能轻松地同时在文本文件中读取和写入行。

    您应该通过使用所需数据创建一个新的临时文件,然后删除旧文件并将临时文件重命名为与原始文件相同的名称来解决此问题。

    按照这些思路应该可以工作(假设 filePath 是原始文件):

    string tempPath = Path.GetTempFileName();
    
    using (var writer = new StreamWriter(tempPath))
    {
        foreach (string line in File.ReadLines(filePath))
        {
            writer.WriteLine(line);
    
            if (line.StartsWith("google"))
                writer.WriteLine("StackOverflow");
        }
    
        // If you want to add other lines to the end of the file, do it here:
    
        writer.WriteLine("This line will be at the end of the file.");
    }
    
    File.Delete(filePath);
    File.Move(tempPath, filePath); // Rename.
    

    如果您只想写入文件末尾而不在文件末尾之前插入任何文本,则可以不使用临时文件,如下所示:

    using (var writer = new StreamWriter(tempPath, append:true))
    {
        writer.WriteLine("Written at end of file, retaining previous lines.");
    }
    

    【讨论】:

    • @KonstantinMokhov 我会将其添加到我的答案中。
    猜你喜欢
    • 1970-01-01
    • 2021-11-25
    • 2017-09-05
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    • 2016-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多