📜  Windows10开发-文件管理

📅  最后修改于: 2020-11-18 10:08:33             🧑  作者: Mango


在任何应用程序中,最重要的事情之一就是数据。如果您是.net开发人员,则可能了解隔离存储,并且通用Windows平台(UWP)应用程序遵循相同的概念。

文件位置

这些是您的应用程序可以访问数据的区域。该应用程序包含某些区域,该区域是该特定应用程序专用的,其他区域则无法访问,但是还有许多其他区域,您可以在其中存储和保存数据到文件中。

文件位置

以下是每个文件夹的简要说明。

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

Applications store local data into a local folder. It can store data up to the limit on the storage device.

3

Roaming folder

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

4

Temp Folder

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

5

Publisher Share

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

6

Credential Locker

Used for secure storage of password credential objects.

7

OneDrive

OneDrive is free online 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.

文件处理API

在Windows 8中,引入了用于文件处理的新API。这些API位于Windows.StorageWindows.Storage.Streams命名空间中。您可以使用这些API代替System.IO.IsolatedStorage命名空间。通过使用这些API,可以更轻松地将Windows Phone应用程序移植到Windows应用商店,并且可以轻松地将应用程序升级到Windows的未来版本。

要访问本地,漫游或临时文件夹,您需要调用以下API-

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

要在本地文件夹中创建新文件,请使用以下代码-

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

这是打开新创建的文件并在该文件中写入一些内容的代码。

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

您可以从本地文件夹再次打开相同的文件,如下面的代码所示。

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); 
   } 
    
}

为了了解数据的读写方式,让我们看一个简单的例子。下面给出的是XAML代码,其中添加了不同的控件。

  
    
    
    
       
            
      .
            
      
            
       
            
    
     

下面给出的是针对不同事件的C#实现,以及用于将数据读取和写入文本文件的FileHelper类的实现。

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/fwlink/?LinkId=402352&clcid=0x409 
 
namespace UWPFileHandling {
 
   ///  
      /// An empty page that can be used on its own or navigated to within a Frame. 
   ///  
    
   public partial class MainPage : Page {
      const string TEXT_FILE_NAME = "SampleTextFile.txt"; 
        
      public MainPage(){ 
         this.InitializeComponent(); 
      }  
        
      private async void readFile_Click(object sender, RoutedEventArgs e) {
         string str = await FileHelper.ReadTextFile(TEXT_FILE_NAME); 
         textBlock.Text = str; 
      }
        
      private async void writeFile_Click(object sender, RoutedEventArgs e) {
         string textFilePath = await FileHelper.WriteTextFile(TEXT_FILE_NAME, textBox.Text); 
      }
        
   } 
    
   public static class FileHelper {
     
      // Write a text file to the app's local folder. 
      
      public static async Task 
         WriteTextFile(string filename, string contents) {
         
         StorageFolder localFolder = ApplicationData.Current.LocalFolder; 
         StorageFile textFile = await localFolder.CreateFileAsync(filename,
            CreationCollisionOption.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.
      
      public static async Task ReadTextFile(string filename) {
         string contents;  
         StorageFolder localFolder = ApplicationData.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; 
      } 
   } 
} 

编译并执行上述代码后,您将看到以下窗口。

文件管理执行

现在,您在文本框中编写了一些内容,然后单击“将数据写入文件”按钮。该程序会将数据写入本地文件夹中的文本文件。如果单击“从文件读取数据”按钮,程序将从同一文本文件读取数据,该文本文件位于本地文件夹中,并将显示在文本块上。

文件管理读写