In this article we are going to see how to access files and folders from your Windows Store application. We come across situation where we need to handle data through some files and place them separately in different folders, to achieve this in Windows store application we need to use the StorageFolder and StorageFile class objects which has predefined methods and properties that can be used to manipulate the files based on the requirement. Also in cases like if the application has permissions to access files and folders in a particular location or a folder we simply need to enumerate and access the files in that location. [more]
Before starting with we need to understand few of the topics which makes it bit easier to understand the flow of the code. We mentioned StorageFolder and StorageFile class plays a major role, but to access the storage we need to make use of few of the namespaces that manages Folders, Files, Permissions and Settings which is Windows.Storage namespace. So in this tutorial what are we going to see, let us take some tasks and see how we can do that with the Windows Store application development.
- Programmatically create a file and store some text.
- Read the file which we created
- Read file properties
- Delete the file programmatically
Let us start developing our app taking in consider the above points are the primary goals that the application should achieve.
Steps:
Open Visual Studio 2012 and create a New Windows Store project with Visual C# template and provide a valid Application Name as shown in the screen below.
Click on OK will create the project solution files and we can see some of the default files added to the solution. First step is to design our XAML page using the controls to get inputs from the end user on the file name, file data etc as shown in the screen below.
XAML Code:
[code:c#]<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<TextBox HorizontalAlignment="Left" Margin="229,36,0,0" TextWrapping="Wrap" Text="" x:Name="txtFileName" FontSize="20" VerticalAlignment="Top" Height="48" Width="394"/>
<TextBlock HorizontalAlignment="Left" Margin="43,49,0,0" FontSize="20" TextWrapping="Wrap" Text="Enter the File Name" VerticalAlignment="Top" Height="48" Width="211"/>
<Button Content="Create File" HorizontalAlignment="Left" Margin="229,305,0,0" FontSize="20" VerticalAlignment="Top" RenderTransformOrigin="-0.163,0.034" Height="47" Width="394" Click="Button_Click_1"/>
<TextBlock HorizontalAlignment="Left" Margin="229,485,0,0" TextWrapping="Wrap" Text="" x:Name="txtOutput" VerticalAlignment="Top" Height="173" Width="394"/>
<TextBox HorizontalAlignment="Left" Margin="229,102,0,0" TextWrapping="Wrap" Text="" x:Name="txtdata" FontSize="20" VerticalAlignment="Top" Height="155" Width="394"/>
<TextBlock HorizontalAlignment="Left" Margin="43,155,0,0" FontSize="20" TextWrapping="Wrap" Text="File data" VerticalAlignment="Top" Height="48" Width="211"/>
<Button Content="Read Data from File" FontSize="20" HorizontalAlignment="Left" Margin="229,417,0,0" VerticalAlignment="Top" Height="47" Width="394" Click="Button_Click_2"/>
<TextBlock HorizontalAlignment="Left" Margin="18,554,0,0" FontSize="20" TextWrapping="Wrap" Text="Data from file" VerticalAlignment="Top" Height="48" Width="211"/>
<Button Content="Delete File and Data" FontSize="20" HorizontalAlignment="Left" Margin="229,678,0,0" VerticalAlignment="Top" Height="47" Width="394" Click="Button_Click_3"/>
<TextBlock HorizontalAlignment="Left" Margin="834,102,0,0" TextWrapping="Wrap" Text="" x:Name="txtStatus" VerticalAlignment="Top" Height="173" Width="394"/>
<TextBlock HorizontalAlignment="Left" Margin="968,49,0,0" FontSize="30" TextWrapping="Wrap" Text="Status" VerticalAlignment="Top" Height="48" Width="211"/>
</Grid>
[/code]Our screen covers all the topics what we have decided to discuss in this tutorial, let us see the code for each of the topic. First let us start with Creating a file with the user inputs data. As mentioned above add the Windows.Storage namespace at the top of the code behind as a Using statement. Now navigate to the first button click event (Create File) button, and write the below code which takes the Filename and the File data to store to a folder. We are going to use StorageFile and StorageFolder class to access the storage API as shown in the code below.
C# Code:
[code:c#]public StorageFolder storageFolder = null;
public StorageFile strStorageFile = null;
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
storageFolder = KnownFolders.DocumentsLibrary;
strStorageFile = await storageFolder.CreateFileAsync(txtFileName.Text.ToString(), CreationCollisionOption.ReplaceExisting);
string strContent = txtdata.Text;
if (!String.IsNullOrEmpty(strContent))
{
await FileIO.WriteTextAsync(strStorageFile, strContent);
txtStatus.Text = "Data and File Created!!!";
}
else
{
txtStatus.Text = "Data is empty to be written in the file";
}
}
Important thing to note here is we have used async in the method which should be specified explicitly as we are going to use await in the file asyn process. This code will get the user input and create a file in the storage folder. Now our next step is to get the file stored and the data which is written to the file, write the below code on the 2nd button click event which will get the data from the respective file as shown in the code below.
C# Code:
[code:c#]private async void Button_Click_2(object sender, RoutedEventArgs e)
{
if (strStorageFile != null)
{
string fileContent = await FileIO.ReadTextAsync(strStorageFile);
txtStatus.Text = fileContent;
}
else
{
txtStatus.Text = "File Not exists!!!";
}
}
Our next task is to delete the file, which is straight forward. To delete the file first get the storage information like the storage folder and file details and process a DeleteAsync method which deletes the files from the storage as shown in the code below.
C# Code:
[code:c#]private async void Button_Click_3(object sender, RoutedEventArgs e)
{
if (strStorageFile != null)
{
string filename = strStorageFile.Name;
await strStorageFile.DeleteAsync();
txtStatus.Text = "File Deleted!!!";
}
else
{
txtStatus.Text = "File already Deleted!!!";
}
}
Consolidated Code:
[code:c#]using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace FilesnFoldersSample
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
public StorageFolder storageFolder = null;
public StorageFile strStorageFile = null;
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
storageFolder = KnownFolders.DocumentsLibrary;
strStorageFile = await storageFolder.CreateFileAsync(txtFileName.Text.ToString(), CreationCollisionOption.ReplaceExisting);
string strContent = txtdata.Text;
if (!String.IsNullOrEmpty(strContent))
{
await FileIO.WriteTextAsync(strStorageFile, strContent);
txtStatus.Text = "Data and File Created!!!";
}
else
{
txtStatus.Text = "Data is empty to be written in the file";
}
}
private async void Button_Click_2(object sender, RoutedEventArgs e)
{
if (strStorageFile != null)
{
string fileContent = await FileIO.ReadTextAsync(strStorageFile);
txtStatus.Text = fileContent;
}
else
{
txtStatus.Text = "File Not exists!!!";
}
}
private async void Button_Click_3(object sender, RoutedEventArgs e)
{
if (strStorageFile != null)
{
string filename = strStorageFile.Name;
await strStorageFile.DeleteAsync();
txtStatus.Text = "File Deleted!!!";
}
else
{
txtStatus.Text = "File already Deleted!!!";
}
}
}
}
Now we are done with the coding, next is to check the application if it process all the request correctly. Before doing that we need to tell the application about the capability it is going to use as Windows Store application runs on the specific capability the is selected by the developer. Since we are going to handle with the documents we need to specify the Document using capability. So how to do that? Open Visual Studio project and navigate to the Package.appxmanifest file from the Solution explorer and navigate to the Capabilities section as shown in the screen below.
Click on Document Library check box in the left side Capabilities listing and navigate to the Declarations tab and select File Type Associations from the Available Declarations listing. In the right side specify the type of file which we are going to use in this sample, if want to use multiple file types then specify all the file types one by one as shown in the screen below.
Now we are done with all the configuration and code, to test the application from the Visual Studio build and execute the application to load it on to the emulator or to the local machine by pressing F5 directly and we can see the application in action as shown in the screens below.
Conclusion:
So in this article we have seen how to achieve using the Files and Folders effectively while developing the Windows Store application. These options can be extended further with additional options like copying files, providing access permissions etc which we will see in detail in our upcoming articles.
No Comments
I am creating a Win8 store app and would like to list all the files present in the storage device in my app. Can you please suggest how this can be acheived?