uwpcharacter-encodingtext-filescp1252

How can I create a ANSI encoded text file in UWP?


I'm currently working on a UWP project and would like to create a text file in ANSI charset (Windows-1252, ISO-8859-1).

The reader of this file only supports ANSI. If the reading side now expects the ANSI format and receives special characters in UTF8 encoding, these ANSI characters from 160 to 255, will be interpreted incorrectly.

In the UWP world you need this:

StorageFile file = await DownloadsFolder.CreateFileAsync("Test.txt");await Windows.Storage.FileIO.WriteTextAsync(file, "Hällö", Windows.Storage.Streams.UnicodeEncoding.Utf8);

Unfortunately, only Unicode encodings can be used here, not ANSI!
The alternative would be

using (TextWriter tw = new StreamWriter(p, true, Encoding.GetEncoding("ISO-8859-1")))

However, this is not allowed out of the UWP sandbox.

So, is there a way to create a simple text file from an UWP application that uses the ANSI character set (Windows-1252, ISO-8859-1)?

Does anyone have an idea?

Regards Torsten


Solution

  • To create an encoding with codepage 1252 (Windows-1252), add the nuget package System.Text.Encoding.CodePages:

    using System.Text;
    
    Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
    
    Encoding encoding = Encoding.GetEncoding(1252); // Western European (Windows)
    

    To write using encoding to DownloadsFolder:

    using Windows.Storage;
    
    string filename = "Test.txt";
    string text = "Hällö";
    
    StorageFile file = await DownloadsFolder.CreateFileAsync(filename, CreationCollisionOption.GenerateUniqueName);
    
    await FileIO.WriteBytesAsync(file, encoding.GetBytes(text));
    

    To read from file using encoding as StreamReader might use encoding autodetection:

    string textRead;
    Encoding currentEncoding;
    using (var r = new StreamReader(await file.OpenStreamForReadAsync(), encoding))
    {
        textRead = r.ReadToEnd();
        currentEncoding = r.CurrentEncoding;
    }
    

    Note; please add a try catch block around the above.