Streamwriter 从文件中读取数据会损坏

Streamwriter 从文件中读取数据会损坏,streamwriter,Streamwriter,我正在从一个TXT文件中读取数据,该文件要求我替换一些现有数据,然后将其写回该文件。问题是,当我将文本写回文件时,文件中有一些特殊字符会损坏 例如,我在文件“foo.txt”中有一个字符串,其中包含以下内容“€rdrf+À[HIGH]”。我的应用程序将文本读入字符串,遍历该行并用值替换[HIGH],然后写回文件。问题是,特殊的文本字符会损坏 以下是代码库的缩写版本: string fileText = System.IO.File.ReadAllText("foo.txt"); fileText

我正在从一个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(); 
如何在不损坏特殊文本字符的情况下读取文件

谢谢
杰伊

我想你需要一个合适的编码

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

我想你需要一个合适的编码

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
试试这个:

        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();
请记住从读卡器和写卡器完成后进行处理。

尝试以下操作:

        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();
请记住在读者和作者写完后进行处理