File Read/ Write Operation In WinJS Applications Using Windows Runtime Component

As we know, WinJS applications are built using HTML/JS/CSS. And for a complete application, we will need async operations like SQLite database operations, web-service calls, and other native XML read-write, and file read-write which cannot be done directly in WinJS applications.

So we have to use Windows Runtime Component to access Native C# methods as discussed in my previous article,

WinJS application with Windows Runtime Component to access Native C# Code

I will show you how to create a text file and write some content in it. After that I will show you how to read that file and display the file content in our HTML page.

Step 1:

Firstly, create a WinJS project as discussed in in my following article. For that we will start with creating a blank Universal Windows App: Please have a look in my previous article: Create Your First WinJS Application

Step 2:

We need to do following things as discussed in my previous article,

  • Add a Windows Runtime Component project and name it ‘WinRuntimes’
  • Delete default class ‘Class1.cs’
  • Add a new class and name it ‘Service’
  • Add WinRuntimes reference in WinJS project
  • Build the project

Step 3:

In Service class, we have to create IAsyncOperation for CreateFile() and ReadFile(). IAsyncOperation represents an asynchronous operation, which returns a result upon completion. This is the return type for many Windows Runtime asynchronous methods that have results but don't report progress. Find more in MSDN.

In CreateFile function, we will pass fileName and fileContent as parameters whereas in ReadFile, we pass filename with the return type string to return the filecontent.

Complete code snippet for Service class:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using Windows.Foundation;  
  7. using Windows.Storage;  
  8.   
  9. namespace WinRuntimes  
  10. {  
  11.     public sealed class Service  
  12.     {  
  13.         public IAsyncOperation<string> CreateFile(string fileName, string fileContent)  
  14.         {  
  15.             return CreateFileHelper(fileName, fileContent).AsAsyncOperation();  
  16.         }  
  17.   
  18.         public IAsyncOperation<string> ReadFile(string fileName)  
  19.         {  
  20.             return ReadFileHelper(fileName).AsAsyncOperation();  
  21.         }  
  22.         private async Task<string> CreateFileHelper(string fileName, string fileContent)  
  23.         {  
  24.             try  
  25.             {  
  26.                 fileName = fileName + ".txt";  
  27.                 StorageFolder folder = ApplicationData.Current.LocalFolder;  
  28.                 StorageFile file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);  
  29.                 await FileIO.WriteTextAsync(file, fileContent);  
  30.                 return "success";  
  31.             }  
  32.             catch (Exception ex)  
  33.             {  
  34.                 return "fail";  
  35.             }  
  36.         }  
  37.         private async Task<string> ReadFileHelper(string fileName)  
  38.         {  
  39.             try  
  40.             {  
  41.                 fileName = fileName + ".txt";  
  42.                 StorageFolder folder = ApplicationData.Current.LocalFolder;  
  43.                 StorageFile file = await folder.GetFileAsync(fileName);  
  44.                 string fileContent = await FileIO.ReadTextAsync(file);  
  45.                 return fileContent;  
  46.             }  
  47.             catch (Exception ex)  
  48.             {  
  49.                 return "fail";  
  50.             }  
  51.         }  
  52.     }  

Step 4:

Add a script.js file and reference it in default.html:

Now in default.html, lets add following things:

  • Input field for file name.
  • Input field for file content to write in file
  • Button with click event to create file
  • Button with click event to read file
  • Div element to display the file content.

Complete html code snippet for default.html is:

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8" />  
  5.     <title>WinJS_FileOperations</title>  
  6.   
  7.     <!-- WinJS references -->  
  8.     <link href="//Microsoft.WinJS.2.0/css/ui-dark.css" rel="stylesheet" />  
  9.     <script src="//Microsoft.WinJS.2.0/js/base.js"></script>  
  10.     <script src="//Microsoft.WinJS.2.0/js/ui.js"></script>  
  11.   
  12.     <!-- WinJS_FileOperations references -->  
  13.     <link href="/css/default.css" rel="stylesheet" />  
  14.     <script src="/js/default.js"></script>  
  15.     <script src="js/script.js"></script>  
  16. </head>  
  17. <body style="margin-left:400px">  
  18.     <p>WinJS File Read Write Operations</p>  
  19.     <input id="txtFileName" placeholder="Enter File Name"/>  
  20.     <br />  
  21.     <input type="text" id="txtFileContent" placeholder="Enter File Content"/>  
  22.     <button id="btnCreateFile" onclick="createFile()">Create File</button>  
  23.     <br />  
  24.     <br />  
  25.     <br />  
  26.     <button id="btnReadFile" onclick="readFile()">Read File</button>  
  27.     <br />  
  28.     <br />  
  29.     <br />  
  30.     <div id="divFileContent"></div>  
  31. </body>  
  32. </html> 
Step 5:

In script.js, we create a service object of Service class and call the createFile and readFile functions to create and read files respectively. Here we have used then function to achieve asynchronous programming.

Complete code snippet for script.js is:

  1. var service = new WinRuntimes.Service();  
  2.   
  3. function createFile() {  
  4.     var fileName = document.getElementById("txtFileName").value;  
  5.     var fileContent = document.getElementById("txtFileContent").value;  
  6.   
  7.     service.createFile(fileName, fileContent).then(function (response) {  
  8.         if (response == "success") {  
  9.             console.log("File Create Successfully");  
  10.         }  
  11.         else {  
  12.             console.log("File creation failed");  
  13.         }  
  14.     });  
  15. }  
  16.   
  17. function readFile() {  
  18.     var fileName = document.getElementById("txtFileName").value;  
  19.       
  20.     service.readFile(fileName).then(function (fileContent) {  
  21.         if (fileContent != "fail") {  
  22.             document.getElementById("divFileContent").innerHTML = fileContent;  
  23.         }  
  24.     });  

Step 6:

Run the application and enter file name and file content and click Create File button.

You can see the new file just created in: Go to "This PC", C, Users > [Your User Name] > AppData, Local, Packages > [App package name] > LocalState,
   

 
 
And finally click the Read File button to read the file content and it is displayed in the div we have added in html. 

That’s it.

Thanks, Happy Coding.

Read more articles on Universal Windows App:

Up Next
    Ebook Download
    View all
    Learn
    View all