Windows10 개발-파일 관리

모든 애플리케이션에서 가장 중요한 것은 데이터입니다. 당신이있는 경우.net 개발자라면 격리 된 저장소에 대해 알고있을 수 있으며 UWP (유니버설 Windows 플랫폼) 애플리케이션을 통해 동일한 개념이 이어집니다.

파일 위치

애플리케이션이 데이터에 액세스 할 수있는 영역입니다. 응용 프로그램에는 특정 응용 프로그램에만 해당되고 다른 응용 프로그램에는 액세스 할 수없는 일부 영역이 포함되어 있지만 파일 내에 데이터를 저장하고 저장할 수있는 다른 영역이 많이 있습니다.

다음은 각 폴더에 대한 간략한 설명입니다.

S. 아니. 폴더 및 설명
1

App package folder

패키지 관리자는 모든 앱 관련 파일을 앱 패키지 폴더에 설치하고 앱은이 폴더의 데이터 만 읽을 수 있습니다.

2

Local folder

응용 프로그램은 로컬 데이터를 로컬 폴더에 저장합니다. 저장 장치의 제한까지 데이터를 저장할 수 있습니다.

Roaming folder

응용 프로그램과 관련된 설정 및 속성은 로밍 폴더에 저장됩니다. 다른 장치도이 폴더의 데이터에 액세스 할 수 있습니다. 응용 프로그램 당 최대 100KB로 제한됩니다.

4

Temp Folder

임시 저장소를 사용하며 애플리케이션이 다시 실행될 때 계속 사용할 수 있다는 보장은 없습니다.

5

Publisher Share

동일한 게시자의 모든 앱에 대한 공유 저장소입니다. 앱 매니페스트에서 선언됩니다.

6

Credential Locker

암호 자격 증명 개체의 보안 저장에 사용됩니다.

7

OneDrive

OneDrive는 Microsoft 계정과 함께 제공되는 무료 온라인 저장소입니다.

8

Cloud

클라우드에 데이터를 저장합니다.

9

Known folders

이러한 폴더는 내 그림, 비디오 및 음악과 같이 이미 알려진 폴더입니다.

10

Removable storage

USB 저장 장치 또는 외장 하드 드라이브 등

파일 처리 API

Windows 8에서는 파일 처리를위한 새로운 API가 도입되었습니다. 이러한 API는Windows.StorageWindows.Storage.Streams네임 스페이스. 대신 이러한 API를 사용할 수 있습니다.System.IO.IsolatedStorage네임 스페이스. 이러한 API를 사용하면 Windows Phone 앱을 Windows Store로 더 쉽게 이식 할 수 있으며 응용 프로그램을 향후 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 코드입니다.

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

다음은 다양한 이벤트에 대한 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 {
 
   /// <summary> 
      /// An empty page that can be used on its own or navigated to within a Frame. 
   /// </summary> 
	
   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<string> 
         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<string> 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; 
      } 
   } 
}

위의 코드를 컴파일하고 실행하면 다음과 같은 창이 나타납니다.

이제 텍스트 상자에 무언가를 쓰고 “Write Data to File”단추. 프로그램은 로컬 폴더의 텍스트 파일에 데이터를 씁니다. 클릭하면“Read Data from File” 버튼을 누르면 프로그램이 로컬 폴더에있는 동일한 텍스트 파일에서 데이터를 읽고 텍스트 블록에 표시합니다.