0

My program is generating a word document by reading another file, but the outpout generates garbled characters example: its generating " Q4 test text", when the output should be "Q4 test text" So far I think its an encoding issue and it looks the following code might need to be changed to fix the issue:

byte[] bytes = file.OpenBinary();

This reads the file, but it looks the encoding is not correct and when the code manipulates and writes this file back, it generates garbled characters. I've researched google and stackExchange and tried few things to fix this, but none of these seems to fix the issue:

//Alternate code 1      
        var sourceBytes = file.OpenBinary();
        byte[] bytes = Encoding.Convert(Encoding.Default, Encoding.UTF8, sourceBytes);
        byte[] bytes = Encoding.Convert(Encoding.UTF8, Encoding.UTF32, sourceBytes);

//Alternate code 2
        System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
        string s = enc.GetString(sourceBytes);
        byte[] bytes = Encoding.UTF8.GetBytes(s);

//Alternate code 3
        var stream = file.OpenBinaryStream();
        var sr = new StreamReader(stream);
        var sw = new StreamWriter(stream);
        var s = sr.ReadToEnd();
        s += "AAA";
        byte[] bytes = Encoding.UTF8.GetBytes(s);
4

0 回答 0