简体   繁体   English

如何在Windows Phone 8.1应用中读取格式化的文本文件?

[英]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? 如何在Windows Phone 8.1应用中读取格式化的文本文件(例如代码文件)? 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;
    }

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. 由于您只是串联由FileIO.ReadLinesAsync返回的各行, FileIO.ReadLinesAsync应改为调用FileIO.ReadTextAsync从头开始以单个字符串获取所有文件内容。 This way you won't need to foreach over them and lose new lines in the process: 这样,您将不需要foreach它们,并且在过程中不会丢失新行:

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. 阅读完毕后,我还添加了一条using语句来正确关闭流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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