Reader Level:
ARTICLE

Writing Text in File With Windows Store Apps Using JavaScript

Posted by Deepak Arora Articles | Windows Store Apps September 18, 2012
In this article I describe how to write in a text file with The help of Windows Store Apps using JavaScript.
  • 0
  • 0
  • 6113

Introduction

In this article I describe how to create a Windows Store App using JavaScript for reading and writing text in a text file. You can create a text file by right-click then New > Text document then rename the document to textfile, or you can create a text file with the help of Windows Store Apps using JavaScript.

I assume you can create a Windows Store App using JavaScript for creating a textfile. For more help visit How to create a text file in Windows Store Apps. The text file textfile.text should be in your documents folder. While you run the Apps if your App does not run then open the package.appxmanifest select in Solution Explorer and check the Document Library in Capability tab and than select declarations and select File Type Associations from the left top drop down list and click on Add after that write textfile at the front of the Name and .txt at the front of the File Type.
 

appex-Windows-store-Apps.jpg
 

Write the following code in page1.html:

<!DOCTYPE html>

<html>

<head>

    <title></title>

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

</head>

<body>

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

        <p>To write text in 'textfile.txt' type n the textbox and click 'Write'. To read the contents ' click 'Read'.</p>

        <textarea rows="5" cols="75" id="textarea"></textarea>

        <br />

        <button id="writeText">Write</button>

        <button id="readText">Read</button>

    </div>

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

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

    </div>

</body>

</html>

Write the following code in default.html:
 

<!DOCTYPE html>

<html>

<head>

    <meta charset="utf-8" />

    <title>SDK Sample</title>

    <link rel="stylesheet" href="//Microsoft.WinJS.1.0/css/ui-dark.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="/utilll/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 in select-page.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 default.js:
 

(function () {

    "use strict";

    var sampleTitle = "Windows Store Apps for writing the text";

    var sampleFile = null;

    var mruToken = null;

    var falToken = null;

    var pages = [

        { url: "/html/page1.html", title: "Creating 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. Use page one to 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();

})();

Write the following code in 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("/utilll/select-page.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();

                });

            });

        }

    };

})();

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("writeText").addEventListener("click", writeText, false);

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

            App.validateFileExistence();

        }

    });

    function writeText() {

        if (App.sampleFile !== null) {

            var textArea = document.getElementById("textarea");

            var userContent = textArea.innerText;

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

            if (userContent !== "") {

                Windows.Storage.FileIO.writeTextAsync(App.sampleFile, userContent).done(function () {

                    outputDiv.innerHTML = "The following text was written to '" + App.sampleFile.name + "':<br /><br />" + userContent;

                },

                function (error) {

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

                });

            } else {

                outputDiv.innerHTML = "The text box is empty, please write something and then click 'Write' again.";

            }

        }

    }

    function readText() {

        if (App.sampleFile !== null) {

            Windows.Storage.FileIO.readTextAsync(App.sampleFile).done(function (fileContent) {

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

                outputDiv.innerHTML = "The following text was read from '" + App.sampleFile.name + "':<br /><br />" + fileContent;

            },

            function (error) {

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

            });

        }

    }

})();


Your output will look like the following:

output-Windows_store-Apps.jpg

Summary

In this article I described how to write in a Text File in Windows Store Apps using JavaScript. I hope you understand well.

COMMENT USING

Trending up