我在一个文件中写了一个Datetime字符串,然后尝试将其读回,但字符串返回交错的零字符。 WP电动工具显示字符串完整" 18.02.2015 12:08:17"。但阅读后看起来像: " 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);
}
}
答案 0 :(得分:1)
您使用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);
}
}