我有以下方法,将文件保存到 Windows Phone 上的 LocalFolder
public async Task<bool> SaveValueByKey(string filename, KeyValuePair<string, string> dataToSave)
{
var appData = ApplicationData.Current;
// Good Save documentation - http://chriskoenig.net/2012/09/07/windows-8-games-and-roaming-data/
StorageFile file = await appData.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);
try
{
// Delete the key if it already exists, then replace.
IEnumerable<string> content = await this.LoadFileContents(filename);
if (content.Any(l => l.StartsWith(string.Format("{0}==", dataToSave.Key))))
{
await this.DeleteKey(filename, dataToSave.Key);
}
await FileIO.WriteTextAsync(file, string.Format("{0}=={1}", dataToSave.Key, dataToSave.Value));
}
catch (Exception)
{
return false;
}
return true;
}
然后我稍后尝试使用此方法加载数据。
public async Task<string> LoadValueFromKey(string filename, string key)
{
var appData = ApplicationData.Current;
StorageFile file = null;
try
{
file = await appData.LocalFolder.GetFileAsync(filename);
}
catch (FileNotFoundException)
{
return string.Empty;
}
catch (Exception)
{
return string.Empty;
}
IEnumerable<string> contents = await this.LoadFileContents(filename);
string element = string.Format("{0}==", key);
if (!contents.Any(line => line.StartsWith(element)))
{
return string.Empty;
}
return contents.First(line => line.StartsWith(element))
.ToString()
.Substring(element.Length);
}
GetFileAsync
即使在调用后向我返回了一个有效的文件对象,调用也会返回null CreateFileAsync
。
我在这里错过了什么吗?我需要声明吗?我没有看到任何与此相关的内容。
编辑
文件名和键值是从存储库传入的,存储库声明它们如下:
private const string tokenFilename = "UserSession.dat";
private const string tokenKey = "UserToken";
编辑 2
引发的异常是带有以下消息的 FileNotFound 异常。
The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Lifestream.App.Mobile.WindowsApp.Services.FileStorageService.<LoadValueFromKey>d__16.MoveNext()
编辑 3
如果我将应用程序作为 Windows 应用程序(这是通用应用程序)运行,则文件将被保存并加载,没有任何问题。如果我以 Windows Phone 为目标,那么当我尝试保存然后加载时会引发 File Not Found 异常。这似乎是特定于手机的,我不知道为什么