c# - c# UWP ReadTextAsync 2 次失败
问题描述
所以我试图从本地文件夹中导入 2 个配置Windows.Storage
。但在第二次它失败了,无一例外。这是我的代码:
public async Task<string> ImportLines(string filename)
{
try
{
Windows.Storage.StorageFile importFile = await StorageFolder.GetFileAsync(filename);
string savedString = await Windows.Storage.FileIO.ReadTextAsync(importFile);
return savedString;
}
catch (Exception)
{
//log
}
}
我将此方法称为:
public async void LoadConfig()
{
if (File.Exists(_textDataHandler.StorageFolder.Path + @"\" + PluginsFilename))
{
string tmp = await _textDataHandler.ImportLines(PluginsFilename);
Plugins = JsonConvert.DeserializeObject<PluginConfiguration>(tmp);
}
else
{
CreateDefaultPluginsConfiguration();
//log
_textDataHandler.CreateFile(_pluginsFilename);
string export = JsonConvert.SerializeObject(Plugins, Formatting.Indented);
_textDataHandler.ExportText(_pluginsFilename, export);
//log
}
if (File.Exists(_textDataHandler.StorageFolder.Path + @"\" + _settingsFilename))
{
string tmp = await _textDataHandler.ImportLines(Settingsfilename);
Config = JsonConvert.DeserializeObject<Configuration>(tmp);
_textDataHandler.CreateFile(Config.DatabaseFilename);
}
else
{
CreateDefaultSettingsConfiguration();
//log
_textDataHandler.CreateFile(_settingsFilename);
string export = JsonConvert.SerializeObject(Config, Formatting.Indented);
_textDataHandler.ExportText(_settingsFilename, export);
//Log
}
}
如果一个配置不存在,则很好,但如果两者都存在,则第二次失败
解决方案
如果您创建了异步方法。请避免与 同步调用GetResult
。您可以在呼叫行前添加await
关键字。
private async void Button_Click(object sender, RoutedEventArgs e)
{
string tmp = await ImportLines(Filename);
}
更新
请尝试使用dataReader
读取文件内容。
public async Task<string> ImportLines(string filename)
{
try
{
StorageFile importFile = await ApplicationData.Current.LocalFolder.GetFileAsync(filename);
var buffer = await FileIO.ReadBufferAsync(importFile);
using (var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(buffer))
{
return dataReader.ReadString(buffer.Length);
}
}
catch (Exception ex)
{
return ex.Message;
}
}
推荐阅读
- c - strcmp() 不适用于 char *array 和 char const 比较
- xcode - Swift 操场在我打字时运行。如何改变它?
- visual-studio-code - “未安装 Flutter Code 扩展”,但已安装数月
- python - 如何使用 pip 安装来自 github 的 egg 文件,而不是在当前目录中,而是在 conda env 目录中?
- scala - 长路径类(输入行太大)
- neo4j - 在 Neo4j 浏览器上找不到“行”选项卡
- xamarin - CustomRenderer 未应用
- mysql - 在数据库中插入一条记录,应该很简单吧
- javascript - netlify/cloudfront/CDN 上的服务工作者缓存问题
- python - 将静态方法与享元装饰器一起使用时出错