Reading Data From File Gets Corrupted

946 views Asked by At

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= iPhoneReferenceText.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

2

There are 2 answers

0
Preet Sangha On

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
0
Murhaf Sousli On

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.