Search code examples
filewindows-phone-8encodingisolatedstorage

Windows Phone 8.0 read file from IsolatedStorage


I write a Datetime string in a file and after that try to read it back, but string returns interlaced with zero characters. WP Power tools show string intact "18.02.2015 12:08:17". But after reading it looks like: "1\08\0.\00\02\0.\02\00\01\05\0 \01\02\0:\00\08\0:\01\07\0"

await FileExtensions.WriteDataToFileAsync("scheduleDateTime.txt", scheduleTime);

var contents = await FileExtensions.ReadFileContentsAsync("scheduleDateTime.txt");


public static async Task<String> ReadFileContentsAsync(string fileName)
{            
    StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;

    if (local != null)
    {
        var file = await local.OpenStreamForReadAsync(fileName);
        using (StreamReader streamReader = new StreamReader(file))
        {
            return streamReader.ReadToEnd();
        }
    }
    else
    {
        return String.Empty;
    }
}

public static async Task WriteDataToFileAsync(string fileName, string content)
{
    byte[] data = Encoding.Unicode.GetBytes(content);

    var folder = ApplicationData.Current.LocalFolder;
    var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

    using (var s = await file.OpenStreamForWriteAsync())
    {
        await s.WriteAsync(data, 0, data.Length);
    }
}

Solution

  • You're saving the file by using UTF-16 encoding, but reading it back using the default encoding (that is, UTF-8). You need to use the same encoding for both case.

    Usually, the recommandation is to use UTF-8 to read and write in files, so you need to change your WriteDataToFileAsync method:

    public static async Task WriteDataToFileAsync(string fileName, string content)
    {
        byte[] data = Encoding.UTF8.GetBytes(content);
    
        var folder = ApplicationData.Current.LocalFolder;
        var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
    
        using (var s = await file.OpenStreamForWriteAsync())
        {
            await s.WriteAsync(data, 0, data.Length);
        }
    }