在Windows Metro风格的Javascript应用程序中读取文件内容

时间:2012-08-29 19:02:20

标签: javascript html windows microsoft-metro windows-runtime

我一直在敲我的头几个小时,阅读(一遍又一遍)我可以在MSDN和Windows开发中心找到的教程;没有任何效果。

我似乎无法从纯文本文件中读取数据!

是的,我添加了文件关联,是的,我已经在项目中添加了声明。

代码来自msdn:

(function () {
    "use strict";

    WinJS.UI.Pages.define("/pages/home/home.html", {
        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        ready: function (element, options) {
            // TODO: Initialize the page here.


            Windows.Storage.FileIO.readTextAsync("AvailableBalance.sv").then(function (contents) {
                // Add code to process the text read from the file
                document.getElementById("AvailableBalanceText").innerText = contents;
            });
        }
    });
});

<h1 id="AvailableBalanceText"></h1>

不起作用。该应用程序加载正常 - 但只是没有从文件中读取(或不显示数据)。

有人可以告诉我这里我做错了吗?

1 个答案:

答案 0 :(得分:1)

readTextAsync doesn't take a file name -- it takes an IStorageFile

您需要在某个地方获取对该文件的引用,而不是仅仅打开它。如果它是用户文件,则需要使用documentsLibrary打开它:

Windows.Storage.KnownFolders.documentsLibrary.getFileAsync("sample.dat").done(function (yourFileHandle) {
    // you now have a file handle.
});

请注意,这是在文档库中。如果您需要访问包中的文件或其他位置(您无法访问Metro中的任意路径,只有库,应用程序的本地数据和包),则需要使用其他API之一。我建议查看sample文件访问权限。

相关问题