简体   繁体   中英

Loading .txt file in C# UWP

I am trying to open a .txt file for my UPW app.

string text;
private async void OpenFile(string fileName)
{            
   StorageFolder localFolder = await ApplicationData.Current.LocalFolder.GetFolderAsync("Beginner");
   try
   {
       StorageFile file = await localFolder.GetFileAsync(fileName + ".txt");                     
       text = await FileIO.ReadTextAsync(file);
       PrintMessage(text);
   }
   catch (Exception)
   {
      PrintMessage("Failed to load file");                
   }
}

public async void PrintMessage(string message)
{
   //Writes message
   MessageDialog msg = new MessageDialog(message);
   await msg.ShowAsync();
}  

public Main() 
{
   OpenFile("WordList");
   PrintMessage(text);
}

The code runs fine when I have PrintMessage(text); after ReadTextAsync . When I delete it, the program will freeze most of the time. When I run it in debugger, it mostly gets done, but sometimes it freezes at line StorageFile file = await localFolder.GetFileAsync(fileName + ".txt"); . I believe there is some problem with async magic.

Also, the text variable in Main() is almost always null even though it should contain text of the file. All I need is a function that will reliably open a .txt file and return (either return return, or like this into global) content of that file. I tried using Task<> but I couldnt make it work either...

Edit: I tried

string text { get; set; }
public async void OpenFileAssist(string fileName)
    {
        await OpenFile(fileName);
    }

public async Task OpenFile(string fileName)
{
    StorageFolder localFolder = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFolderAsync("Beginner");
    try
    {
        StorageFile file = await localFolder.GetFileAsync(fileName + ".txt");
        text = await FileIO.ReadTextAsync(file);
    }
    catch (Exception)
    {
        PrintMessage("File does not exist");
    }
}

But it still does not work... When I call OpenFileAssist() from Main() the text variable is still null. :( If I open it in debugger and go step by step it works, though.

I got solution by using

private async void Page_Loaded(object sender, RoutedEventArgs e)

See this page , especially the example using TaskScheduler.FromCurrentSynchronizationContext(). It helped me a lot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM