在 Windows Phone 8 中读取文件:值不在预期范围内

在 Windows Phone 8 中读取文件:值不在预期范围内

问题描述:

当打开存储在我的项目中的文件时,我真的遇到了问题.我需要打开一些文件(pdf、html、...)并且遇到同样的问题:值不在预期范围内.

I'm really problems when open files stored in my project. I need open some files (pdf, html,...) and ever has the same problem: Value does not fall within the expected range.

我尝试了几种方法:

a)

private async Task<string> ReadFileContentsAsync(string fileName)
{
    StorageFolder foldera = ApplicationData.Current.LocalFolder;

    try
    {
        Stream filea = await foldera.OpenStreamForReadAsync("/Assets/Data/htm/" + fileName + ".htm");


        ...
    }
    catch (Exception e)
    {
        Debug.WriteLine("ERROR ReadFileContentsAsync " + e.Message);
        return null;
    }
}

b)

private async Task<string> ReadFileContentsAsync(string fileName)
{
    try
    {
        StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(
                new Uri("ms-appdata:///Assets/Data/htm/" + fileName + ".htm", UriKind.RelativeOrAbsolute));

        ...
    }
    catch (Exception e)
    {
        Debug.WriteLine("ERROR ReadFileContentsAsync " + e.Message);
        return null;
    }
}

c)

StorageFile file2 = await StorageFile.GetFileFromApplicationUriAsync(
                                            new Uri("ms-appdata:///Assets/Data/pdf/lc_dossier_acceso_castellana.pdf", UriKind.Absolute));

当我按下按钮时会启动此操作.

This actions are launched when I push a button.

我不知道发生了什么.

文件位于 Solution'NewProject'/NewProject/Assets/Data/*/

The files are in Solution'NewProject'/NewProject/Assets/Data/*/

我注意到如果在文件路径中使用斜杠 / 会出现该错误.相反,如果我使用反斜杠 \ 我可以获得文件.

I noticed that I get that error if I use the slash / in the path to the file. Instead, if I use backslash \ I can get the files.

尝试以下方式:

StorageFile sFile = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(@"Assets\Data\htm\" + fileName + ".htm");

var fileStream = await sFile.OpenStreamForReadAsync();

请注意,您必须在路径字符串之前放置一个 @ 以避免将 \ 解释为转义字符.

Note that you have to place an @ before the path string to avoid the intepretation of \ as scape character.

您也可以通过这种方式获取文件流:

You could also get the file stream this way:

var fileStream = File.OpenRead("Assets/Data/htm/" + fileName + ".htm");