Deletion and Geting Property of Text File in Windows Store Apps Using JavaScript

Introduction

In this article I describe how to delete a text file and how to get the properties of a text file in Windows Store Apps using JavaScript. I assume you already know how to create a textfile. You can create a text file by right-clicking then selecting from the context menu New > Text document or you can also create a text file in Windows Store Apps using JavaScript. In my previous article I describe how to create and copy a text file, you can also visit Creation and copy of Text file .

It is necessary that in your document folder is a text file named textfile.txt. For creating this app you create two folders in your project namely html and utill. In your html folder add two HTML pages, page1.html and page2.html. In your js folder add two pages script1.js and script2.js. In your utill folder add two pages select.html and utill.js. In package.appxmanifest select capabilities and select the document library checkbox then select Declarations and at the left side click on add and select File type Associations then write textfile as the name and .txt at File type.

appex-Windows-Store-Apps.png


Now write the following code for default.html:

<!DOCTYPE html>

<html>

<head>

    <meta charset="utf-8" />

    <title>Apps</title>

    <link rel="stylesheet" href="//Microsoft.WinJS.1.0/css/ui-light.css" />

    <script src="//Microsoft.WinJS.1.0/js/base.js"></script>

    <script src="//Microsoft.WinJS.1.0/js/ui.js"></script>

    <link rel="stylesheet" href="/css/default.css" />

    <script src="/utill/utill.js"></script>

    <script src="/js/default.js"></script>

</head>

<center><body role="application">

    <div id="rootGrid">

        <div id="content">

            <h1 id="featureLabel"></h1>

            <div id="contentHost"></div>

        </div>

        </div>

</body></center>

</html>

Write the following code for page1.html:
 

<!DOCTYPE html>

<html>

<head>

    <title></title>

    <script src="/js/script1.js"></script>

</head>

<body>

    <div data-win-control="app.PageInput">

        <p>To retrieve properties for 'textfile.txt' click on button.</p>

        <button id="showProperties" class="action">Properties</button>

    </div>

    <div data-win-control="app.PageOutput">

        <div id="output"></div>

    </div>

</body>

</html>

Write the following code for page2.html:
 

<!DOCTYPE html>

<html>

<head>

    <title></title>

    <script src="/js/script2.js"></script>

</head>

<body>

    <div data-win-control="app.PageInput">

        <p>To delete 'textfile.txt' click 'Delete'.</p>

        <button id="delete" class="action">Delete</button>

    </div>

    <div data-win-control="app.PageOutput">

        <div id="output"></div>

    </div>

</body>

</html>

Write the following code for select.html:
 

<!DOCTYPE html>

<html>

<head>

    <title></title>

</head>

<body>

    <div class="options">

        <h3 id="listLabel">Select Page:</h3>

        <select id="PageSelect" aria-labelledby="listLabel">

        </select>

    </div>

</body>

</html>

Write the following code in script1.js:
 

(function () {

    "use strict";

    var Page = WinJS.UI.Pages.define("/html/Page1.html", {

        ready: function (element, options) {

            document.getElementById("showProperties").addEventListener("click", showProperties, false);

            app.validateFileExistence();

        }

    });

    var dateAccessedProperty = "System.DateAccessed";

    var fileOwnerProperty = "System.FileOwner";

    function showProperties() {

        if (app.sampleFile !== null) {

            var outputDiv = document.getElementById("output");

           outputDiv.innerHTML = "Filename: " + app.sampleFile.name + "<br />";

            outputDiv.innerHTML += "File type: " + app.sampleFile.fileType + "<br />";

            app.sampleFile.getBasicPropertiesAsync().then(function (basicProperties) {

                outputDiv.innerHTML += "Size: " + basicProperties.size + " bytes<br />";

                outputDiv.innerHTML += "Date modified: " + basicProperties.dateModified + "<br />";

                return app.sampleFile.properties.retrievePropertiesAsync([fileOwnerProperty, dateAccessedProperty]);

            }).done(function (extraProperties) {

                var propValue = extraProperties[dateAccessedProperty];

                if (propValue !== null) {

                    outputDiv.innerHTML += "Date accessed: " + propValue + "<br />";

                }

                propValue = extraProperties[fileOwnerProperty];

                if (propValue !== null) {

                    outputDiv.innerHTML += "File owner: " + propValue;

                }

            },

            function (error) {

                WinJS.log && WinJS.log(error, "sample", "error");

            });

        }

    }

})();


Write the following code in script2.js:
 

(function () {

    "use strict";

    var Page = WinJS.UI.Pages.define("/html/Page2.html", {

        ready: function (element, options) {

            document.getElementById("delete").addEventListener("click", deleteFile, false);

            app.validateFileExistence();

        }

    });

    function deleteFile() {

        if (app.sampleFile !== null) {

            var outputDiv = document.getElementById("output");

            app.sampleFile.deleteAsync().done(function () {

                app.sampleFile = null;

                outputDiv.innerHTML = "The file 'textfile.txt' was deleted.";

            },

            function (error) {

                WinJS.log && WinJS.log(error, "sample", "error");

            });

        }

    }

})();


write the following code in default.js:
 

(function () {

    "use strict";

    var sampleTitle = "Deletion and retrival of property of a file";

    var sampleFile = null;

    var mruToken = null;

    var falToken = null;

    var Pages = [

        { url: "/html/Page1.html", title: "propertyof file" },

        { url: "/html/Page2.html", title: "deleting a file" }

    ];

    function activated(eventObject) {

        if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {

            eventObject.setPromise(WinJS.UI.processAll().then(function () {

                var url = WinJS.Application.sessionState.lastUrl || Pages[0].url;

                return WinJS.Navigation.navigate(url);

            }));

        }

    }

    WinJS.Navigation.addEventListener("navigated", function (eventObject) {

        var url = eventObject.detail.location;

        var host = document.getElementById("contentHost");

        host.winControl && host.winControl.unload && host.winControl.unload();

        WinJS.Utilities.empty(host);

        eventObject.detail.setPromise(WinJS.UI.Pages.render(url, host, eventObject.detail.state).then(function () {

            WinJS.Application.sessionState.lastUrl = url;

        }));

    });

    function validateFileExistence() {

        Windows.Storage.KnownFolders.documentsLibrary.getFileAsync("textfile.txt").done(

            function (file) {

                app.sampleFile = file;

            },

            function (err) {

                app.sampleFile = null;

                WinJS.log && WinJS.log("The file 'textfile.txt' does not exist.");

            }

        );

    };

    WinJS.Namespace.define("app", {

        sampleTitle: sampleTitle,

        Pages: Pages,

        validateFileExistence: validateFileExistence,

        sampleFile: sampleFile,

        mruToken: mruToken,

        falToken: falToken

    });

 

    WinJS.Application.addEventListener("activated", activated, false);

    WinJS.Application.start();

})();


Write the following code for utill.js:
 

(function () {

    var lastError = "";

    var lastStatus = "";

    var PageInput = WinJS.Class.define(

        function (element, options) {

            element.winControl = this;

            this.element = element;

            new WinJS.Utilities.QueryCollection(element)

                        .setAttribute("role", "main")

                        .setAttribute("aria-labelledby", "inputLabel");

            element.id = "input";

            this.addInputLabel(element);

            this.addDetailsElement(element);

            this.addPagesPicker(element);

        }, {

            addInputLabel: function (element) {

                var label = document.createElement("h2");

                label.textContent = "Input";

                label.id = "inputLabel";

                element.parentNode.insertBefore(label, element);

            },

            addPagesPicker: function (parentElement) {

                var Pages = document.createElement("div");

                Pages.id = "Pages";

                var control = new PageSelect(Pages);

                parentElement.insertBefore(Pages, parentElement.childNodes[0]);

            },

 

            addDetailsElement: function (sourceElement) {

                var detailsDiv = this._createDetailsDiv();

                while (sourceElement.childNodes.length > 0) {

                    detailsDiv.appendChild(sourceElement.removeChild(sourceElement.childNodes[0]));

                }

                sourceElement.appendChild(detailsDiv);

            },

            _createDetailsDiv: function () {

                var detailsDiv = document.createElement("div");

 

                new WinJS.Utilities.QueryCollection(detailsDiv)

                            .addClass("details")

                            .setAttribute("role", "region")

                            .setAttribute("aria-labelledby", "descLabel")

                            .setAttribute("aria-live", "assertive");

                var label = document.createElement("h3");

                label.textContent = "Description";

                label.id = "descLabel";

                detailsDiv.appendChild(label);

                return detailsDiv;

            },

        }

    );

      var PageOutput = WinJS.Class.define(

        function (element, options) {

            element.winControl = this;

            this.element = element;

            new WinJS.Utilities.QueryCollection(element)

                        .setAttribute("role", "region")

                        .setAttribute("aria-labelledby", "outputLabel")

                        .setAttribute("aria-live", "assertive");

            element.id = "output";

            this._addOutputLabel(element);

            this._addStatusOutput(element);

        }, {

            _addOutputLabel: function (element) {

                var label = document.createElement("h2");

                label.id = "outputLabel";

                label.textContent = "Output";

                element.parentNode.insertBefore(label, element);

            },

            _addStatusOutput: function (element) {

                var statusDiv = document.createElement("div");

                statusDiv.id = "statusMessage";

                element.insertBefore(statusDiv, element.childNodes[0]);

            }

        }

    );

    var currentPageUrl = null;

    WinJS.Navigation.addEventListener("navigating", function (evt) {

        currentPageUrl = evt.detail.location;

    });

    WinJS.log = function (message, tag, type) {

        var isError = (type === "error");

        var isStatus = (type === "status");

        if (isError || isStatus) {

            var statusDiv = /* @type(HTMLElement) */ document.getElementById("statusMessage");

            if (statusDiv) {

                statusDiv.innerText = message;

                if (isError) {

                    lastError = message;

                    statusDiv.style.color = "blue";

                } else if (isStatus) {

                    lastStatus = message;

                    statusDiv.style.color = "green";

                }

            }

        }

    };

    var PageSelect = WinJS.UI.Pages.define("/utill/select.html", {

        ready: function (element, options) {

            var that = this;

            var selectElement = WinJS.Utilities.query("#PageSelect", element);

            this._selectElement = selectElement[0];

            app.Pages.forEach(function (s, index) {

                that._addPage(index, s);

            });

            selectElement.listen("change", function (evt) {

                var select = evt.target;

                if (select.selectedIndex >= 0) {

                    var newUrl = select.options[select.selectedIndex].value;

                    WinJS.Navigation.navigate(newUrl).then(function () {

                        setImmediate(function () {

                            document.getElementById("PageSelect").setActive();

                        });

                    });

                }

            });

            selectElement[0].size = (app.Pages.length > 5 ? 5 : app.Pages.length);

            if (app.Pages.length === 1) {

               selectElement[0].setAttribute("multiple", "multiple");

            }

        },

        _addPage: function (index, info) {

            var option = document.createElement("option");

            if (info.url === currentPageUrl) {

                option.selected = "selected";

            }

            option.text = (index + 1) + ") " + info.title;

            option.value = info.url;

            this._selectElement.appendChild(option);

        }

    });

    function activated(e) {

        WinJS.Utilities.query("#featureLabel")[0].textContent = app.sampleTitle;

    }

    WinJS.Application.addEventListener("activated", activated, false);

    WinJS.Namespace.define("app", {

        PageInput: PageInput,

        PageOutput: PageOutput

    });

    document.Testapp = {

        getLastError: function () {

            return lastError;

        },

 

        getLastStatus: function () {

            return lastStatus;

        },

 

        selectPage: function (PageID) {

            PageID = PageID >> 0;

            var select = document.getElementById("PageSelect");

            var newUrl = select.options[PageID - 1].value;

            WinJS.Navigation.navigate(newUrl).then(function () {

                setImmediate(function () {

                    document.getElementById("PageSelect").setActive();

                });

            });

        }

    };

})(); 


The output of the property file looks like the following:


property-Windows-store-Apps.png

The output of the delete file looks like the following:


delete-Windows_store-Apps.png

Up Next
    Ebook Download
    View all
    Learn
    View all