1

我正在从 TXT 文件中读取数据,需要我替换一些现有数据,然后将其写回文件。问题是,当我将文本写回文件时,文件中的特殊字符会损坏。

例如,我在文件“foo.txt”中有一个字符串,它具有以下“€rdrf +À [HIGH]”。我的应用程序将文本读入字符串,遍历该行并将 [HIGH] 替换为一个值,然后写回文件。问题是,特殊文本字符已损坏。

这是代码库的缩写版本:

string fileText = System.IO.File.ReadAllText("foo.txt");
fileText= iPhoneReferenceText.Replace("[HIGH]", low);
TextWriter tw = new StreamWriter("Path");
tw.WriteLine(fileText);
tw.Close(); 

如何在不损坏特殊文本字符的情况下从文件中读取?

谢谢杰

4

2 回答 2

1

我认为您需要适当的编码

string fileText = System.IO.File.ReadAllText("foo.txt", Encoding.XXXX);
.
.
tw = new StreamWriter("path", Encoding.XXXX);
.
.

其中 XXXX 是以下之一:

  System.Text.ASCIIEncoding
  System.Text.UnicodeEncoding
  System.Text.UTF7Encoding
  System.Text.UTF8Encoding
于 2010-10-08T21:47:26.340 回答
0

尝试这个 :

        string filePath = "your file path";
        StreamReader reader = new StreamReader(filePath);
        string text = reader.ReadToEnd();
        // now you edit your text as you want
        string updatedText = text.Replace("[HIGH]", "[LOW]");

        reader.Dispose(); //remember to dispose the reader so you can overwrite on the same file
        StreamWriter writer = new StreamWriter(filePath);
        writer.Write(text, 0, text.Length);
        writer.Dispose(); //dispose the writer
        Console.ReadLine();

读者和作者写完后记得Dispose。

于 2012-03-04T21:32:09.407 回答