从文件中读取数据已损坏

时间:2010-10-08 21:39:40

标签: streamwriter

我正在读取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(); 

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

由于 杰

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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();

记得在读者和作者完成后处理。