【问题标题】:Write to a text file after specified string?在指定字符串后写入文本文件?
【发布时间】:2015-07-16 19:10:42
【问题描述】:

我的代码是

Dictionary<string,string> members = new Dictionary<string,string>();
//.. initialization of this dictionary

                using (StreamWriter file = new StreamWriter(pathToFile))
                    foreach (var entry in members)
                        file.WriteLine("[{0} {1}]", entry.Key, entry.Value);

我需要在文件“testString”中可能出现的第一个指定字符串之后编写这些内容。这怎么能轻松完成?

【问题讨论】:

  • 所以你想追加到文件中某个字符串的位置之后?
  • 文件可以在这个字符串之后继续 -(在中心附加或粘贴 - 类似这样)
  • 那么您是否要在该位置插入新文本,但将其余文本保留在文件中?
  • 是的,插入是正确的词
  • 如果它是一个小文件,您可以将其全部读入一个字符串,插入您的文本,然后将整个字符串写回。如果它是一个大文件,您需要移动前一个文件,将文本从旧文件复制到“testString”到新文件,写入新数据,然后从旧文件复制其余文本。

标签: c#


【解决方案1】:

您是否需要在文件中间插入数据(即 引用:“在这个文件中可能出现的第一个指定字符串之后写这个东西”)?

Dictionary<string, string> members = new Dictionary<string, string>();

String lineToFind = "testString";

// Let's read the file up in order to avoid read/write conflicts
var data = File
  .ReadLines(pathToFile)
  .ToList();

var before = data
  .TakeWhile(line => line != lineToFind)
  .Concat(new String[] {lineToFind}); // add lineToFind

var after = data
  .SkipWhile(line => line != lineToFind)
  .Skip(1); // skip lineToFind

var stuff = members
  .Select(entry => String.Format("[{0} {1}]", entry.Key, entry.Value));

File.WriteAllLines(pathToFile, before
  .Concat(stuff)
  .Concat(after));

【讨论】:

  • 需要在 WriteAllLines 之后关闭文件吗?
【解决方案2】:

您可以从文件中读取所有内容并将其存储为字符串。然后找到指定子字符串的索引并插入新值。然后使用以下命令写回文本文件:

using (StreamWriter file = new StreamWriter(pathToFile, false)){}

【讨论】:

    【解决方案3】:

    创建一个临时文件并将所有数据逐行写入其中,同时遍历所有行搜索指定的字符串并将数据插入到找到它的位置。同时最大限度地减少内存消耗。

    Dictionary<string, string> members = new Dictionary<string, string>();
    //.. initialization of this dictionary
    
    string pathToFile = "";
    
    string tempfile = Path.GetTempFileName();   //create a temp file
    using (var writer = new StreamWriter(tempfile))
    using (var reader = new StreamReader(pathToFile))
    {
        //if file is not ended
        while (!reader.EndOfStream)
        {
            //get next line
            string line = reader.ReadLine();
    
            //write it to the "temp file"
            writer.WriteLine(line);
    
            //search in the line, if found, insert your data
            if (line.Contains("search what you need"))
            {
                foreach (var entry in members)
                    writer.WriteLine("[{0} {1}]", entry.Key, entry.Value);
            }                    
        }
    }
    
    //overwrite the actual file with temp file
    File.Copy(tempfile, pathToFile, true);
    

    致谢:他回答here时,我使用了Jake的逻辑。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-06
      相关资源
      最近更新 更多