Windows Phone 8.0 从 IsolatedStorage 读取文件

Windows Phone 8.0 read file from IsolatedStorage

我在文件中写了一个日期时间字符串,然后尝试读回它,但字符串 returns 与零个字符交错。 WP Power 工具显示字符串完整“18.02.2015 12:08:17”。但阅读后看起来像: "1[=15=].[=16=][=16=].[=17=][=17=] [=18=]:[=19=][=19=]:[=20=]"

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

您正在使用 UTF-16 编码保存文件,但使用默认编码(即 UTF-8)读回文件。您需要对这两种情况使用相同的编码。

一般情况下,建议使用UTF-8读写文件,所以你需要改变你的WriteDataToFileAsync方式:

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