v.g.
v.g.

Reputation: 1076

How to read formatted text file in a Windows Phone 8.1 app?

How to read a formatted text file (say code file) in Windows Phone 8.1 app? I read a text file like this below, but when it has one line comments, for example it messes the whole read content..

private async Task<string> GetFileContent()
    {
        string str = "";

        string strResourceReference = "ms-appx:///Helpers/MyJavaScriptFile.js";
        StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(strResourceReference, UriKind.Absolute));
        Stream sr = await file.OpenStreamForReadAsync();
        await FileIO.ReadLinesAsync(file);

        foreach (string s in await FileIO.ReadLinesAsync(file))
        {
            str += s;
        }

        return str;
    }

Upvotes: 0

Views: 70

Answers (1)

Damir Arh
Damir Arh

Reputation: 17865

Since you're just concatenating the individual lines returned by FileIO.ReadLinesAsync, you should call FileIO.ReadTextAsync instead to get all the file contents in a single string from the start. This way you won't need to foreach over them and lose new lines in the process:

private async Task<string> GetFileContent()
{
    string strResourceReference = "ms-appx:///Helpers/MyJavaScriptFile.js";
    StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(strResourceReference, UriKind.Absolute));
    using (Stream sr = await file.OpenStreamForReadAsync())
    {
        return await FileIO.ReadTextAsync(file);
    }
}

I also added a using statement to properly close the stream, once you're done reading.

Upvotes: 1

Related Questions