File Handling In Windows 10 Universal App

In Windows 10 universal app there are three types of locations you can use for file operations:

  • Local Folder
  • Roaming Folder
  • Temporary Folder

Let’s see the steps:

Create new Windows universal project and name it.

Create two buttons; one for Read and Write operation and one for TextBox to get the input from the user.

XAML Code:

  1. <Page.BottomAppBar>  
  2.     <AppBarIsOpen="True" IsSticky="True">  
  3.         <StackPanel Orientation="Horizontal">  
  4.             <AppBarButton Name="WriteBtn" Icon="Add" Click="WriteBtn_Click" Label="Write"></AppBarButton>  
  5.             <AppBarButton Name="readBtn" Icon="Read" Click="readBtn_Click" Label="Read"></AppBarButton>  
  6.         </StackPanel>  
  7.         </AppBar>  
  8. </Page.BottomAppBar>  
  9. <Grid Background="{ThemeResourceApplicationPageBackgroundThemeBrush}">  
  10.     <StackPanel>  
  11.         <TextBox x:Name="editBox"></TextBox>  
  12.     </StackPanel>  
  13. </Grid>  
Now go to code behind page and write the following code. You can create the file in any location. Here I created the file in LocalFolder location.
  1. private async void WriteBtn_Click(object sender, RoutedEventArgs e)  
  2. {  
  3.     var file = awaitApplicationData.Current.LocalFolder.CreateFileAsync("FileName.txt", CreationCollisionOption.ReplaceExisting);  
  4.     var stream = awaitfile.OpenAsync(FileAccessMode.ReadWrite);  
  5.     using(var writer = newDataWriter(stream.GetOutputStreamAt(0)))  
  6.     {  
  7.         writer.WriteString(editBox.Text.ToString());  
  8.         awaitwriter.StoreAsync();  
  9.         awaitwriter.FlushAsync();  
  10.     }  
  11. }  
Write the following code in Read button click event.
  1. private async void readBtn_Click(object sender, RoutedEventArgs e)  
  2. {  
  3.     var file = awaitApplicationData.Current.LocalFolder.GetFileAsync("FileName.txt");  
  4.     var stream = awaitfile.OpenAsync(FileAccessMode.Read);  
  5.     using(var reader = newDataReader(stream.GetInputStreamAt(0)))  
  6.     {  
  7.         var bytes = awaitreader.LoadAsync((uint) stream.Size);  
  8.         var s = reader.ReadString(bytes);  
  9.         MessageDialogshowDialog = newMessageDialog(s.ToString());  
  10.         showDialog.ShowAsync();  
  11.     }  
  12. }  
Now run the app and write something in the textbox and click the “Write” button. The program will write the data into the text file in a local folder. Then click on the  “Read” button; it will read the data from the same text file, which is located in the local folder and will display it on message dialog like the following output screen.

run

For more file operations like delete, rename, copy, move, etc. visit my previous article:

 

Read more articles on Windows 10:


Similar Articles