首页 > 解决方案 > 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
            }


        }

如果一个配置不存在,则很好,但如果两者都存在,则第二次失败

标签: c#uwpio

解决方案


如果您创建了异步方法。请避免与 同步调用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;
    }
}

推荐阅读