写单词到行尾的麻烦

时间:2014-11-17 15:05:12

标签: c# visual-studio-2010 file

我可以将新行粘贴到文件中,

   string filePath = @"C:\Users\user\Documents\1.txt";
   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.Write("StackOverflow");
        }
    }
    File.Delete(filePath);
    File.Move(tempPath, filePath);

我怎么能写在行尾?也许我需要解析这一行,把我的话放到line.length -position?

2 个答案:

答案 0 :(得分:1)

writer.WriteLine(line);将追加行尾字符(\r\n),您需要在检查条件是否满足后附加字符串,然后再使用WriteLine,如:

foreach (string line in File.ReadLines(filePath))
{
   if (line.StartsWith("google"))
   {
        writer.WriteLine(line + "StackOverflow");
   }
   else
   {
        writer.WriteLine(line);          
   }
}

答案 1 :(得分:0)

只需将您想要的内容连接到行尾即可。

writer.WriteLine(line + " Add this to the end of the line");