Copying a Text File With the Help of Windows Store Apps Using JavaScript

Introduction

In this article I describe how to copy a text file (.txt file) in Windows Store Apps using JavaScript. For copying a file it is necessary to have a text file named textfile.txt in your Documents folder. You can create the file textfile.txt by right-click then new > text document and than renaming that document to textfile.text. Or you can create this file with the help of Windows Store Apps using JavaScript. I also describe how to create a text file named textfile.txt by Windows Store apps. For this you create two folders namely html and utill. In the html folder you add two pages page1.html and page2.html and in the utill folder you add a HTML page select.html and a JavaScript page.utill.js.

html folder:

  • page1.html
  • page2.html

utill folder:

  • select.html
  • utill.js

js folder:

  • page1.js
  • page2.js

copyfile-Windows-Store-apps-using-JavaScript.png

For your default.html page write the following code:

<!DOCTYPE html>

<html>

<head>

    <meta charset="utf-8" />

    <title>app</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>

For your page1.html page write the following code:
 

<!DOCTYPE html>

<html>

<head>

    <title></title>

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

</head>

<body>

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

        <p>Create a new textfile.txt file. File will be created in the Documents library.</p>

        <button id="createFile">Create</button>

        <br />

        <br />

    </div>

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

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

    </div>

</body>

</html>

For your age2.html page write the following code:
 

<!DOCTYPE html>

<html>

<head>

    <title></title>

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

</head>

<body>

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

        <p>Create a new textfile.txt file. File will be created in the Documents library.</p>

        <button id="createFile">Create</button>

        <br />

        <br />

    </div>

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

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

    </div>

</body>

</html>

For your select.html write the following code:
 

<!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>

For your page1.js write the following code:
 

<!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>

For your page2.html write the following code:
 

<!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>

For your utill.js write the following code:
 

(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();

                });

            });

        }

    };

})();

For your default.js page write the following code:

 

(function () {

    "use strict";

    var sampleTitle = "Creating and copying a text file";

    var sampleFile = null;

    var mruToken = null;

    var falToken = null;

    var pages = [

        { url: "/html/page1.html", title: "Creating a text file" },

        { url: "/html/page2.html", title: "copying 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("'textfile.txt'not exist. first create this file.", "sample", "error");

            }

        );

    };

    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();

})();

Output for creating the file:

filecreadted-Windows-Store-Apps-using-JavaScript.jpg


Output for Copying the file:


file-copied-Windows-store-Apps-Using-JavaScript.png

Up Next
    Ebook Download
    View all
    Learn
    View all