English 中文(简体)
Windows 10 - File Management
  • 时间:2024-11-05

Windows10 Development - File Management


Previous Page Next Page  

In any apppcation, one of the most important thing is the data. If you are .net developer, you might know about the isolated storage and the same concept follows through the Universal Windows Platform (UWP) apppcations.

File Locations

These are the areas where your apppcation can access the data. The apppcation contains some area, which is private to that particular apppcation and is inaccessible to the others, but there are many other areas, where you can store and save your data inside a file.

File Location

Given below are the brief descriptions of each folder.

S.No. Folder & Description
1

App package folder

Package manager installs all the app’s related files into the App package folder, and app can only read data from this folder.

2

Local folder

Apppcations store local data into a local folder. It can store data up to the pmit on the storage device.

3

Roaming folder

Setting and properties related to apppcation is stored in roaming folder. Other devices can also access data from this folder. It has pmited size up to 100KB per apppcation.

4

Temp Folder

Use of temporary storage and there is no guarantee that it will still be available when your apppcation runs again.

5

Pubpsher Share

Shared storage for all the apps from the same pubpsher. It is declared in app manifest.

6

Credential Locker

Used for secure storage of password credential objects.

7

OneDrive

OneDrive is free onpne storage that comes with your Microsoft account.

8

Cloud

Store data on the cloud.

9

Known folders

These folders already known folders such as My Pictures, Videos, and Music.

10

Removable storage

USB storage device or external hard drive etc.

File Handpng APIs

In Windows 8, new APIs were introduced for file handpng. These APIs are located in the Windows.Storage and Windows.Storage.Streams namespaces. You can use these APIs instead of the System.IO.IsolatedStorage namespace. By using these APIs, it will be easier to port your Windows Phone app to the Windows Store, and you can easily upgrade your apppcations to future versions of the Windows.

To access local, roaming or temp folders, you need to call these APIs −

StorageFolder localFolder = ApppcationData.Current.LocalFolder; 
StorageFolder roamingFolder = ApppcationData.Current.RoamingFolder; 
StorageFolder tempFolder = ApppcationData.Current.TemporaryFolder; 

To create a new file in a local folder use the following code −

StorageFolder localFolder = ApppcationData.Current.LocalFolder; 
StorageFile textFile = await localFolder.CreateFileAsync(filename, 
   CreationColpsionOption.ReplaceExisting);

Here is the code to open the newly created file and write some content in that file.

using (IRandomAccessStream textStream = await textFile.OpenAsync(FileAccessMode.ReadWrite)) { 
	
   using (DataWriter textWriter = new DataWriter(textStream)){
      textWriter.WriteString(contents); 
      await textWriter.StoreAsync(); 
   } 
		
}

You can open the same file again, from the local folder as shown in the code given below.

using (IRandomAccessStream textStream = await textFile.OpenReadAsync()) { 

   using (DataReader textReader = new DataReader(textStream)){
      uint textLength = (uint)textStream.Size; 
      await textReader.LoadAsync(textLength); 
      contents = textReader.ReadString(textLength); 
   } 
	
}

To understand how the reading and writing of the data works, let us have a look at a simple example. Given below is the XAML code in which different controls are added.

<Page
   x:Class = "UWPFileHandpng.MainPage" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:local = "using:UWPFileHandpng" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibipty/2006" 
   mc:Ignorable = "d">  
	
   <Grid Background = "{ThemeResource ApppcationPageBackgroundThemeBrush}"> 
	
      <Button x:Name = "readFile" Content = "Read Data From File"  
         HorizontalApgnment = "Left" Margin = "62,518,0,0"  
         VerticalApgnment = "Top" Height = "37" Width = "174"  
         Cpck = "readFile_Cpck"/> 
			
      <TextBox x:FieldModifier = "pubpc" x:Name = "textBox"  
         HorizontalApgnment = "Left" Margin = "58,145,0,0" TextWrapping = "Wrap"  
         VerticalApgnment = "Top" Height = "276" Width = "245"/>.
			
      <Button x:Name = "writeFile" Content = "Write Data to File"
         HorizontalApgnment = "Left" Margin = "64,459,0,0"  
         VerticalApgnment = "Top" Cpck = "writeFile_Cpck"/>
			
      <TextBlock x:Name = "textBlock" HorizontalApgnment = "Left"  
         Margin = "386,149,0,0" TextWrapping = "Wrap"  
         VerticalApgnment = "Top" Height = "266" Width = "250"  
         Foreground = "#FF6231CD"/> 
			
   </Grid> 
	 
</Page>

Given below is the C# implementation for different events and also the implementation of the FileHelper class for reading and writing data to the text file.

using System; 
using System.IO; 
using System.Threading.Tasks; 

using Windows.Storage; 
using Windows.Storage.Streams; 
using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls;
  
// The Blank Page item template is documented at 
   http://go.microsoft.com/fwpnk/?LinkId=402352&clcid=0x409 
 
namespace UWPFileHandpng {
 
   /// <summary> 
      /// An empty page that can be used on its own or navigated to within a Frame. 
   /// </summary> 
	
   pubpc partial class MainPage : Page {
      const string TEXT_FILE_NAME = "SampleTextFile.txt"; 
		
      pubpc MainPage(){ 
         this.InitiapzeComponent(); 
      }  
		
      private async void readFile_Cpck(object sender, RoutedEventArgs e) {
         string str = await FileHelper.ReadTextFile(TEXT_FILE_NAME); 
         textBlock.Text = str; 
      }
		
      private async void writeFile_Cpck(object sender, RoutedEventArgs e) {
         string textFilePath = await FileHelper.WriteTextFile(TEXT_FILE_NAME, textBox.Text); 
      }
		
   } 
	
   pubpc static class FileHelper {
     
      // Write a text file to the app s local folder. 
	  
      pubpc static async Task<string> 
         WriteTextFile(string filename, string contents) {
         
         StorageFolder localFolder = ApppcationData.Current.LocalFolder; 
         StorageFile textFile = await localFolder.CreateFileAsync(filename,
            CreationColpsionOption.ReplaceExisting);  
				
         using (IRandomAccessStream textStream = await 
            textFile.OpenAsync(FileAccessMode.ReadWrite)){ 
             
               using (DataWriter textWriter = new DataWriter(textStream)){ 
                  textWriter.WriteString(contents); 
                  await textWriter.StoreAsync(); 
               } 
         }  
			
         return textFile.Path; 
      }
		
      // Read the contents of a text file from the app s local folder.
	  
      pubpc static async Task<string> ReadTextFile(string filename) {
         string contents;  
         StorageFolder localFolder = ApppcationData.Current.LocalFolder; 
         StorageFile textFile = await localFolder.GetFileAsync(filename);
			
         using (IRandomAccessStream textStream = await textFile.OpenReadAsync()){
             
            using (DataReader textReader = new DataReader(textStream)){
               uint textLength = (uint)textStream.Size; 
               await textReader.LoadAsync(textLength); 
               contents = textReader.ReadString(textLength); 
            }
				
         }
			
         return contents; 
      } 
   } 
} 

When the above code is compiled and executed, you will see the following window.

File Management Execute

Now, you write something in the textbox and cpck “Write Data to File” button. The program will write the data into the text file in a local folder. If you cpck on “Read Data from File” button, the program will read the data from the same text file, which is located in the local folder and will display it on the text block.

File Management Read Write Advertisements