开发者

Reading Data From File Gets Corrupted

I am reading data from a TXT file that requires me to replace some of the existing data, and then write it back to the file. The issue is, there are special characters in the file that get corrupted when I write the text back to the file.

For example, I have a string in a file "foo.txt" that has the following "€rdrf +À [HIGH]". My application reads the text into a string, goes through the line and replaces [HIGH] with a value, and then writes back to the file. The issue is, the special text characters get corrupted.

Here is an abbreviated version of the code base:

string fileText = System.IO.File.ReadAllText("foo.txt");
fileText= iPhoneRe开发者_运维问答ferenceText.Replace("[HIGH]", low);
TextWriter tw = new StreamWriter("Path");
tw.WriteLine(fileText);
tw.Close(); 

How do I read from the file without corrupting the special text characters?

Thanks Jay


You need an appropriate Encoding I think

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

Where XXXX is one of:

  System.Text.ASCIIEncoding
  System.Text.UnicodeEncoding
  System.Text.UTF7Encoding
  System.Text.UTF8Encoding


Try this :

        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();

Remember to Dispose after finishing from the reader and the writer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜