13 - Manipulating file data in Windows Apps

In Window store apps; if an app is uninstalled from a device the app data will be lost. If we need data even after the un- installation of apps we can save data in files. In window store apps we can read and write data to a file. To read and write data to a file, firstly we need access that file.

Files can be saved to a particular location in the App installation directory, App data locations and download folder by default.

Files located at some other locations can be accessed by declaring capabilities and file pickers.

File access locations accessible by default

Every window store app can access the following locations by default:

App Installation directory

This is the folder where app is installed. It is read only folder. We can retrieve StorageFolder using following code:

Windows.Storage.StorageFolder installedLocation= Windows.AppliactionModel.Package.Current.InstalledLocation;

Here installedLocation is the instance of StorageFolder. It represents the installation directory of the app.

We can also retrieve a file directly using the app URI

using Windows.Storage;

StorageFile file=await StorageFile.GetFileFromApplicationUriAsync (“ms-appx:///datafile.txt”);

Here file is the instance of StorageFile class. GetFileFromAppliactionUriAsync() method will return instance of the file datafile.txt, which is installed in app installation directory (ms-appx).

App data locations

This is the location where an app can store data. It can be local, temporary or roaming folder. To access these locations:

Retrieve app data folder using following code:

using Windows.Storage;

StorageFolder localfolder=ApplicationData.Current.LocalFolder;

Here localfolder is the instance of StorageFolder class. It can access the files and folders saved in the local folder of the app.

We can also retrieve files or folders directly by using app URI:

using Windows.Storage;

StorageFile file=await StorageFile.GetFileFromApplicationUriAsync(“ms-appdata:///local/datafile.txt”);

Here file is the instance of StorageFile class and GetFileFromAppliactionUriAsync() is the method that will return the instance of the file datafile.txt.

Downloads folder

 It is the folder where all the files downloaded from internet are saved. All the apps can access this folder by default.  We can also create a file or folder in the Downloads folder by using CreateFileAsync() method or CreateFolderAsync() method.

using Windows.Storage;

  StorageFile newFile=await DownloadsFolder.CreateFileAsync(“datafile1.txt”);

Accessing files using Capabilities

Window store apps can access files stored in different locations using capabilities that need to be set in the manifest file. Some locations, capabilities and their API are listed below:

Location

Capability

Storage API

 

Documents Library

DocumentsLibrary

KnownFolders.DocumentsLibrary

 

Music Library

MusicLibrary

KnownFolders.MusicLibrary

 

Pictures library

PicturesLibrary

KnownFolders.PicturesLibrary

 

Videos library

VideosLibrary

KnownFolders.VideosLibrary

 

Homegroup libraries

  • MusicLibrary
  • PicturesLibrary
  • VideosLibrary

KnownFolders.HomeGroup

 

Removable devices

RemovableDevices

KnownFolders.RemovableDevices

 

Media server devices

  • MusicLibrary
  • PicturesLibrary
  • VideosLibrary

KnownFolders.MediaServer Devices

Accessing files using File Pickers

File picker allows user to access files explicitly. A user cannot access any file from the installation directory using file picker. With the help of file pickers, a user can access files and folders from various locations. Using file pickers user can pick documents, pictures and videos from a local hard disk.

Interface of file picker

          

There are following components of file picker interface:

Current Location

          

The group of items, which the user can choose from

          

List of locations, present in the form of drop down list, from where a user can browse files and folders:

          

File open picker

Let consider an example where we have to use Image viewer app. The app has a ListBox control to display the list of images and image control to display the selected image on the right side. Here we have to use file open picker to access image file stored at a particular location on hard disk. We can add an app bar that contain a Add Button.

We have to associate an event handler, Button_Tapped with the Tapped event of Add button. For this we can use the following Interface and code:

          

To make function above event handler we need to define UnSnapped variable and declare an instance file of StorageFile class in MainPage:Page class. We also define EnsureUnSnapped() method, that ensures that file open picker will open in UnSnapped view only.

private async void Button_Tapped (object sender, TappedRoutedEventArgs e)
{
 EnsureUnsnapped(); 
 if (unSnapped) 
 {
 FileOpenPicker openPicker = new FileOpenPicker(); 
 openPicker.ViewMode = PickerViewMode.List; 
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
 openPicker.FileTypeFilter.Add (".jpg");
 openPicker.FileTypeFilter.Add (".gif");
file = await openPicker.PickSingleFileAsync();
if (file != null) 
{
lstboxPictureList.Items.Add (file.Path); 
 }
 }
 }

File Save picker

File save picker enable to save the file. For eg in a writing pad app, user can add information in plain text. The app also provides the users to save the file using file save picker. To enable the saving functionality we should use event handler like Button_Tapped with the Tapped event of the save button in app like:

StorageFile file; 
bool unSnapped = true;
 async void EnsureUnsnapped() 
{
unSnapped = ((ApplicationView.Value != ApplicationViewState.Snapped) || ApplicationView.TryUnsnap());

 if (!unSnapped)
{
MessageDialog msg = new MessageDialog("Cannot open file picker in snapped view "); await msg.ShowAsync();
}
}

Here savePicker is the instance of FileSavePicker class. Which specifies the start location of the file picker to Documents library using SuggestedStartLocation property. Here FileTypeChoices property is used to create a format in which file can be saved. SuggestedFile Name is used to specify the name of file. PickSaveFileAsync() method is used to save the file.

Accessing file in a particular folder:

To access files stored at a particular folder first we need to specify the location where it is saved. For this we need to create a collection of files and folders as follows:

private async void Button_Tapped(object sender, TappedRoutedEventArgs e)
{
 EnsureUnsnapped();
if (unSnapped)
{
FileSavePicker savePicker = new FileSavePicker(); 
savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary; savePicker.FileTypeChoices.Add ("Plain Text", new List<string=() { ".txt" });
 savePicker.SuggestedFileName = "New Document"; 
await savePicker.PickSaveFileAsync ();
 }
 }

Here picturesFolder is the instance of StorageFolder class, which holds the location of PicturesLibrary folder.GetFilesAsync() method is used to fetch the filed of PicturesLibrary folder in IReadOnlyList interface element, fileList. A string Files: is appended to the outputText instance.

Writing to a file

To save the content of a TextBox in a file we need to write information to the file using WriteTextAsync() method of FileIO class. To implement this functionality we can use following code:

StorageFile file= await savePicker.PickSaveFileAsync();
 if(file !=null)
{
 await Windows.Storage.FileIO.WriteTextAsync (file, "This is Windows 8"); 
}

Write file using buffer

To write a file using buffer in the form of bytes we need to write code:

StorageFile file = await savePicker.PickSaveFileAsync();
 if (file != null)
{
var buffer = Windows.Security.Cryptography.CryptographicBuffer.ConvertStringToBinary( txtContent.Text,Windows.Security.Cry ptography.BinaryStringEncoding.Utf8);
 await Windows.Storage.FileIO.WriteBufferAsync(file, buffer); 
}

Write file using Stream

StorageFile file = await savePicker.PickSaveFileAsync(); 
if (file != null)
{
Try
{var stream = await file.OpenAsync (FileAccessMode.ReadWrite);
 var outputStream = stream.GetOutputStreamAt(0);
 DataWriter dataWriter = new DataWriter(outputStream); dataWriter.WriteString (txtContent.Text);
 await dataWriter.StoreAsync();
await outputStream.FlushAsync();
}
catch { } 
} 

Here file is the reference of StorageFile class, which is used to save a file. OpenAsync is a method which receives parameter FileAccessMode.ReadWrite, that is used to read and write to a file. Variable outputStream is used to contain value of the beginning position of outputStream. StoreAsync() method is used to store the content in the file. FlushAsync() method is used to clear the stream.

Reading from a file:

To read a file we first need to use file open picker to open the text file from a particular location on the system.

Using ReadTextAsync() method we can directly read a file. This method belongs to FileIO class.

If we want to read a file from Documents Library we can use the following code:

StorageFolder storageFolder = KnownFolders.DocumentsLibrary; 
StorageFile dataFile1 = await storageFolder.GetFileAsync ("datafile.txt"); 
txtFileContents.Text = await Windows.Storage.FileIO.ReadTextAsync (dataFile1);

Here instance of StorageFolder is used to access DocumentsLibrary folder. Datafile.txt is accessed through GetFileAsync() method.

Read a file using Stream

We can read textual or other information using a stream. To read a file using stream we first need to use input stream. Input stream can be used for the writing purpose in a file.

Like us on Facebook