【问题标题】:c# edit txt file without creating another file (without StreamWriter)c#编辑txt文件而不创建另一个文件(没有StreamWriter)
【发布时间】:2011-11-16 12:14:38
【问题描述】:

因为我使用的是非拉丁字母,所以如果我使用 StreamWriter,字符是不正确的。

        String line;
        StreamReader sr = new StreamReader(@"C:\Users\John\Desktop\result.html");
        line = sr.ReadLine();
        while (line != null)
        {
            line = sr.ReadLine();
            if (line.Contains("</head>"))
            {
                line = "<img src=\"result_files\\image003.png\"/>" + line;
            }
        }
        sr.Close();

这里我正在编辑要在文件中编辑的字符串,但我没有将它保存在同一个文件中。该怎么做?

【问题讨论】:

  • 我认为在您的代码 sn-p 中您只是在堆中操作字符串,StreamReader 仅用于读取而不是用于写入,您要编写哪个非拉丁字母?是 > 标志吗?
  • 可以在StreamWriter上设置编码
  • 但我并不总是有这个文件。也许编码会有所不同。
  • 从您上次的评论中不清楚问题出在哪里。读取文件或将其写回新文件时是否收到不正确的字符?您真的想要一个新文件还是只想修改现有文件?

标签: c# file stream


【解决方案1】:

如果您使用接受编码的StreamWriter constructors 之一,您应该不会遇到错误字符的任何问题。您还跳过了阅读方法中的第一行。

Encoding encoding;
StringBuilder output = new StringBuilder();
using (StreamReader sr = new StreamReader(filename))
{
    string line;
    encoding = sr.CurrentEncoding;
    while ((line = sr.ReadLine()) != null)
    {
        if (line.Contains("</head>"))
        {
            line = "<img src=\"result_files\\image003.png\"/>" + line;
        }
        output.AppendLine(line);
    }
}
using (StreamWriter writer = new StreamWriter(filename, false, encoding))
{
    writer.Write(output.ToString());
}

【讨论】:

  • 这给了我一个空输出。
  • 我刚刚重新测试过,对我来说效果很好。我只是用它来复制一个文本文件。
  • 没问题。我刚刚编辑了示例以始终使用原始文件中的编码。
  • 其实我又出现了奇怪的字符。
  • 你能发布一个我可以测试的文件的链接吗?
【解决方案2】:

我认为最简单的方法是

  1. 以读/写模式打开文件

  2. 从文件中读取所有内容

  3. 在内存中进行修改

  4. 将其重写回文件而不是附加..

【讨论】:

    【解决方案3】:

    您使用 StreamReader。名称说明了它的功能。阅读!

    脏代码

            if (File.Exists(fileName))
            {
                int counter = 1;
                StringBuilder sb = new StringBuilder();
                foreach (string s in File.ReadAllLines(fileName, Encoding.Default))
                {
                    if (s.Contains("</head>"))
                    {
                        s= "<img src=\"result_files\\image003.png\"/>" + line;
                    }
    
                        sb.AppendLine(s);
    
                    counter++;
                }
    
                File.WriteAllText(fileName, sb.ToString(), Encoding.Default);
            }
    

    【讨论】:

      猜你喜欢
      • 2013-03-28
      • 1970-01-01
      • 2011-01-30
      • 2017-07-19
      • 1970-01-01
      • 1970-01-01
      • 2013-06-25
      • 1970-01-01
      相关资源
      最近更新 更多