File Operation in Windows Store Application Using C#

This article will demonstrate how to work with files in Windows Store Applications.

The main operations performed on files are:

Create, Read, Update and Delete

In this article, we see how to manage and perform those operations on binary data in Files in the Windows Store Application using C#.

In the later section I will show you an example of creating a file, adding data to it, saving it, reopening it and appending some more data to it.

Instructions to be followed.

Step 1

In this example I use a Blank Windows Store Application template using XAML.

Step 2

Here is the XAML markup for the UI:

<Page

    x:Class="FileStreamAccess.MainPage"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:local="using:FileStreamAccess"

    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

    mc:Ignorable="d">

 

    <Grid Background="Black">

       <Grid.ColumnDefinitions>

              <ColumnDefinition Width="auto"/>

              <ColumnDefinition/>

       </Grid.ColumnDefinitions>

       <Grid.RowDefinitions>

              <RowDefinition Height="120"/>

              <RowDefinition Height="Auto" MinHeight="145"/>

              <RowDefinition/>

       </Grid.RowDefinitions>

        <StackPanel Grid.Column="0" Grid.Row="1" Margin="30,0,0,0">

            <TextBox x:Name="InputTextBox" Grid.Column="0" Height="94"  Width="350" Grid.Row="0" TextWrapping="Wrap"/>

            <Button x:Name="CreateFileButton" Content="Create File" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Column="0"  Grid.Row="1" Height="39" Width="204" Click="CreateFileClicked"/>

       <Button x:Name="OpenAndReadFileButton" Content="Open and Read File" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Column="0" Grid.Row="1" Height="39" Width="204" Click="OpenReadClicked"/>

       <Button x:Name="AppendAndSaveButton" Content="Append and Save" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Column="0"  Grid.Row="1" Height="39" Width="204" Click="AppendSaveClicked"/>

       <Button x:Name="DeleteFileButton" Content="Delete File" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Column="0" Grid.Row="1" Height="39" Width="204" Click="DeleteClicked"/>

        </StackPanel>           

        <TextBlock Grid.Column="0" HorizontalAlignment="Left" Height="10"  Grid.Row="2" TextWrapping="Wrap" Text="Status" VerticalAlignment="Top" Width="37"/>

        <TextBlock x:Name="StatusTextBlock" TextWrapping="Wrap" Text="" Grid.Column="0" FontSize="25"  Grid.Row="2" Foreground="White" LineStackingStrategy="BlockLineHeight"/>

    </Grid>

</Page>

Step 3

Now, here is how file operations can be done.

To create a file:
 

private async void CreateFile(object sender, Windows.UI.Xaml.RoutedEventArgs e)

{

     StorageFolder storageFolder = ApplicationData.Current.LocalFolder;

     this.MyFile = await storageFolder.CreateFileAsync(MainPage.fileName, CreationCollisionOption.ReplaceExisting);

     await Windows.Storage.FileIO.WriteTextAsync(MyFile, InputTextBox.Text);

     StatusTextBlock.Text = "The file '" + MyFile.Name + "' was created.";

}

In the preceding code the CreateFileAsync method will create a new file or overwrites one if it already exists.

To open the file:

private async System.Threading.Tasks.Task OpenFile()

{

    StorageFolder storageFolder = ApplicationData.Current.LocalFolder;

    this.MyFile = await storageFolder.GetFileAsync(MainPage.fileName);

    StatusTextBlock.Text = "The file '" + MyFile.Name + "' was loaded.";

}

In the preceding code GetFileAsync method is used to load the file.

To read the open file:

private async System.Threading.Tasks.Task ReadFromFile()

{

     using (IRandomAccessStream sessionRandomAccess =await this.MyFile.OpenAsync(FileAccessMode.Read))

     {

        if (sessionRandomAccess.Size > 0)

        {

            byte[] array3 = new byte[sessionRandomAccess.Size];

            IBuffer output = await sessionRandomAccess.ReadAsync(array3.AsBuffer(0, (int)sessionRandomAccess.Size),(uint)sessionRandomAccess.Size,InputStreamOptions.Partial);

            string reRead = Encoding.UTF8.GetString(output.ToArray(), 0, (int)output.Length);

            StatusTextBlock.Text ="The Content of File is:"+ Environment.NewLine + reRead;

        }

        else

        {

            StatusTextBlock.Text = "File is empty";

        }

    }

}

In the preceding code once the file is in open mode, we open an instance of an object that implements IRandomAccessStream. Check the length, then use the ReadAsync method to read from the randomAccessStream into the byte array.

Next we convert the byte array into a string using the UTF8 encoding. In our case we are the ones writing to the file so we know that the Encoding is UTF8.


To save the file after updating it.

To save the changes after updating its content, we need to perform the following tasks.

  • Geting the content from the TextBox.
  • Next we open a RandomAccessStream again but this time in read-write mode.
  • Move the stream's current pointer to the end of the stream by using the Seek command.
  • Now we convert the input string into a Byte Array.
  • Next we increase the length of the stream to accommodate the new data.
  • Finally we write to the stream.

Here is the code:

private async void AppendSaveClicked(object sender, Windows.UI.Xaml.RoutedEventArgs e)

{

    StorageFile file = this.MyFile;

    if (file != null)

    {

       string userContent = InputTextBox.Text;

       if (!String.IsNullOrEmpty(userContent))

       {

          using (IRandomAccessStream sessionRandomAccess = await file.OpenAsync(FileAccessMode.ReadWrite))

          {

             Stream stream = sessionRandomAccess.AsStreamForWrite();

             if (stream.Length > 0)

             {

                stream.Seek(stream.Length, SeekOrigin.Begin);

             }

             byte[] array = Encoding.UTF8.GetBytes(userContent);

             stream.SetLength(stream.Length + array.Length); 

             await stream.WriteAsync(array, 0, array.Length);

             await stream.FlushAsync();

             await sessionRandomAccess.FlushAsync();

          }

          ResetScenarioOutput();

          StatusTextBlock.Text = "Date is Appnded Successfully to the File";

       }

       else

       {

         StatusTextBlock.Text = @"The text box is empty, please write something and then click 'Write' again.";

       }

    }

    else

    {

                StatusTextBlock.Text = @"File not open!
    }

}

To delete the file:

private async void DeleteFile(object sender, Windows.UI.Xaml.RoutedEventArgs e)

{

     try

     {

       this.ResetScenarioOutput();

       StorageFile file = this.MyFile;

        if (file == null)

        {

             await OpenFile();

        }

        if (file != null)

        {

           string filename = file.Name;

           await file.DeleteAsync();

           this.MyFile = null;

           StatusTextBlock.Text = "The file '" + filename + "' was deleted";

        }

        else

        {

            StatusTextBlock.Text = "The file does not exist";

        }

     }

     catch (FileNotFoundException)

     {

       this.NotifyUserFileNotExist();

     }

}

In the preceding code I simply call the DeleteAsync() method to delete the file.

Step 4

Now, build your app and run it using F5.

You will see various buttons to perform various operations on the file. Click according to use.

File-operation-in-windows-store-apps.jpg

Conclusion

Using this article, we learned how we can create, read, append and delete data to/from a file using a stream.


Similar Articles