Search code examples
c#windows-runtimewinrt-async

C# Windows Store App - File IO using async/await causes timeouts and InvalidOperationException


this is my first post on this site and I searched high and wide to get my code to work. Like the title says, it's a WinRT App and I'm having difficulty with File IO. What I want to do is read in a text file stored in a folder that is inside the application installation directory and that contains lines of data that I'll feed into an List<>.

public static async void GetStations()
    {
        try
        {
            using (var stream = await Windows.Storage.ApplicationData.Current.LocalFolder.OpenStreamForReadAsync(@"MyApp\Data\file.txt"))
            {
                using (var streamReader = new StreamReader(stream))
                {
                    while (streamReader.Peek() >= 0)
                    {
                        string line = await streamReader.ReadLineAsync();
                        //do something with 
                    }
                }

            }
        }
        catch (Exception e)
        {
            ...
        }
        finally
        {
            ...
        }
    }

the problem is I am getting file not found errors when trying to run it. Can anyone help? If you require that I post more information, I can... Thanks in advance.


Solution

  • If you are distributing your file as a part of your application package then Package.Current.InstalledLocation is the right location. ApplicationData.Current.LocalFolder contains only files that have been put there by your application.

    The correct code would be:

    public static async void GetStations()
    {
        try
        {
            using (var stream = await Windows.ApplicationModel.Package.Current.InstalledLocation.OpenStreamForReadAsync(@"Data\file.txt"))
            {
                using (var streamReader = new StreamReader(stream))
                {
                    while (streamReader.Peek() >= 0)
                    {
                        string line = await streamReader.ReadLineAsync();
                        //do something with 
                    }
                }
    
            }
        }
        catch (Exception e)
        {
            //...
        }
        finally
        {
            //...
        }
    }
    

    The file must be included in you project inside Data folder and have Build Action set to Content.