StorageFolder.GetFoldersAsync Method

Definition

Overloads

GetFoldersAsync()

Gets the subfolders in the current folder.

GetFoldersAsync(CommonFolderQuery)

Gets the subfolders in the current folder. When the value of the query argument is something other than CommonFolderQuery.DefaultQuery, gets a list of virtual folders that represent containers for groups of files in the subfolders of the current folder. Files are grouped into folders based on the specified value from the CommonFolderQuery enumeration.

GetFoldersAsync(CommonFolderQuery, UInt32, UInt32)

Gets an index-based range of folders from the list of all subfolders in the current folder. When the value of the query argument is something other than CommonFolderQuery.DefaultQuery, gets a list of virtual folders that represent containers for groups of files in the subfolders of the current folder. Files are grouped into folders based on the specified value from the CommonFolderQuery enumeration.

GetFoldersAsync()

Gets the subfolders in the current folder.

C#
public IAsyncOperation<IReadOnlyList<StorageFolder>> GetFoldersAsync()
Returns
IAsyncOperation<IReadOnlyList<StorageFolder>>

When this method completes successfully, it returns a list of the subfolders in the current folder. The list is of type IReadOnlyList&lt;StorageFolder >. Each folder in the list is represented by a StorageFolder object.

Exceptions
UnauthorizedAccessException

You don't have permission to access the contents of the current folder.

Examples

The following example shows how to get the contents of the subfolders in the user's Pictures folder, grouped by month, by calling the GetFoldersAsync(CommonFolderQuery, UInt32, UInt32) method. (Files from the root of the current folder are not included.) This example returns a maximum of 4 folders, starting with the folder at index 0. Since the CommonFolderQuery.GroupByMonth option sorts dates in descending order (that is, from newest to oldest), this example returns folders for the 4 most recent months for which the user has photos. Each folder contains all the user's photos from that month.

Before you run the following example, enable the Pictures Library capability in the app manifest file.

C#
using Windows.Storage;
using Windows.Storage.Search;
using System.Threading.Tasks;
using System.Diagnostics; // For writing results to Output window.

// Get the user's Pictures folder.
// Enable the corresponding capability in the app manifest file.
StorageFolder picturesFolder = KnownFolders.PicturesLibrary;

// Get the files in the subfolders of the user's Pictures folder,
// grouped by month. Get only the first 4 folders (months).
IReadOnlyList <StorageFolder> groupedItems = await picturesFolder.GetFoldersAsync(CommonFolderQuery.GroupByMonth, 0, 4);

// Iterate over the results and print the list of folders
// and files to the Visual Studio Output window.
foreach (StorageFolder folder in groupedItems)
{
    Debug.WriteLine(folder.Name);

    // To iterate over the files in each folder, uncomment the following lines. 
    // foreach(StorageFile file in await folder.GetFilesAsync())
    //    Debug.WriteLine(" " + file.Name);
}
C++
// Get the user's Pictures folder.
// Enable the corresponding capability in the app manifest file.
StorageFolder^ picturesFolder = KnownFolders::PicturesLibrary;

// Get the files in the user's Pictures folder, grouped by month.
// Get only the first 4 folders (months).
create_task(picturesFolder->GetFoldersAsync(CommonFolderQuery::GroupByMonth)).then([=](IVectorView<StorageFolder^>^ itemsInFolder) {
 //Iterate over the results and print the list of file groups
 // to the visual studio output window
 for (auto it = itemsInFolder->First(); it->HasCurrent; it->MoveNext())
 {
  StorageFolder^ file = it->Current;
  String^ output = file->Name + "
";
  OutputDebugString(output->Begin());
 }
});

Remarks

This query is a shallow query that returns only subfolders in the current folder.

The following table lists methods of the StorageFolder class that get a list of subfolders. The table identifies shallow queries that only return subfolders from the current folder, and deep queries that return the contents of nested subfolders, grouped into virtual folders.

Some methods take a value from the CommonFolderQuery enumeration.

  • When you use the DefaultQuery option with any folder, the query returns a list of subfolders in the file system.
  • When you use an option other than DefaultQuery with a library folder, the query returns a list of virtual folders that represent containers for files from the subfolders of the current folder. (Files from the current folder are not included.) The files are grouped into virtual folders based on the specified value from the CommonFolderQuery enumeration. For example, if you specify GroupByMonth, the query returns a list of virtual folders such as July 2014, August 2014, and September 2014. > > [!TIP] > You can use the DefaultQuery option with any folder; you can use the other options from the CommonFolderQuery enumeration only with library folders, such as the Pictures library, or the Homegroup folder.

To get deep query results from a folder that's not a library folder, call the CreateFolderQueryWithOptions(QueryOptions) method and specify Deep as the value of the FolderDepth property of the QueryOptions object.

MethodCreate a shallow query that only returns subfolders from the current folderCreate a deep query that returns all nested subfolders
GetFoldersAsync()Default behavior of this method.N/A
GetFoldersAsync(CommonFileQuery)Specify the DefaultQuery option.For a library folder, specify an option other than DefaultQuery.
GetFoldersAsync(CommonFileQuery, UInt32, UInt32)Specify the DefaultQuery option.For a library folder, specify an option other than DefaultQuery.
CreateFolderQuery()Default behavior of this method.N/A
CreateFolderQuery(CommonFileQuery)Specify the DefaultQuery option.For a library folder, specify an option other than DefaultQuery.
CreateFolderQueryWithOptions(QueryOptions)
  • Default behavior of this method if none of the following options are specified. - or -
  • Specify DefaultQuery as the value of CommonFolderQuery when you instantiate the QueryOptionsobject. - or -
  • Specify Shallow as the value of the FolderDepth property of the QueryOptions object.
See Also

GetFoldersAsync(CommonFolderQuery)

Gets the subfolders in the current folder. When the value of the query argument is something other than CommonFolderQuery.DefaultQuery, gets a list of virtual folders that represent containers for groups of files in the subfolders of the current folder. Files are grouped into folders based on the specified value from the CommonFolderQuery enumeration.

C#
public IAsyncOperation<IReadOnlyList<StorageFolder>> GetFoldersAsync(CommonFolderQuery query)
Parameters
query
CommonFolderQuery

One of the enumeration values that specifies how to group the files into folders and determines whether the query is shallow or deep.

Returns
IAsyncOperation<IReadOnlyList<StorageFolder>>

When this method completes successfully, it returns a list of subfolders. When the value of the query argument is something other than CommonFolderQuery.DefaultQuery, this method returns a list of virtual folders that represent containers for groups of files in the subfolders of the current folder. (Files from the current folder are not included.) The files are grouped as specified by query. The list is of type IReadOnlyList&lt;StorageFolder >. Each folder in the list is represented by a StorageFolder object.

Exceptions
UnauthorizedAccessException

You don't have permission to access the contents of the current folder.

See Also

GetFoldersAsync(CommonFolderQuery, UInt32, UInt32)

Gets an index-based range of folders from the list of all subfolders in the current folder. When the value of the query argument is something other than CommonFolderQuery.DefaultQuery, gets a list of virtual folders that represent containers for groups of files in the subfolders of the current folder. Files are grouped into folders based on the specified value from the CommonFolderQuery enumeration.

C#
public IAsyncOperation<IReadOnlyList<StorageFolder>> GetFoldersAsync(CommonFolderQuery query, UInt32 startIndex, UInt32 maxItemsToRetrieve)
Parameters
query
CommonFolderQuery

One of the enumeration values that specifies how to group the files into folders and determines whether the query is shallow or deep.

startIndex
UInt32

The zero-based index of the first folder in the range to retrieve.

maxItemsToRetrieve
UInt32

The maximum number of folders to retrieve.

Returns
IAsyncOperation<IReadOnlyList<StorageFolder>>

When this method completes successfully, it returns a list of subfolders. When the value of the query argument is something other than CommonFolderQuery.DefaultQuery, this method returns a list of virtual folders that represent containers for groups of files in the subfolders of the current folder. (Files from the current folder are not included.) The files are grouped as specified by query. The list is of type IReadOnlyList&lt;StorageFolder >. Each folder in the list is represented by a StorageFolder object.

Exceptions
UnauthorizedAccessException

You don't have permission to access the contents of the current folder.

See Also



Segoe MDL2 icon guidelines - UWP app developer _ Microsoft Docs.pdf





My Windows 10 UWP app is calling a WebAPI web service that I have created. I need to send a JPG file from the UWP app to the server so that the server can store it into another application.

I am using using Windows.Web.Http; as recommended for UWP and using Windows Authentication to connect to the server.

When I perform a POST using the following code, I get the IRandomAccessStream does not support the GetInputStreamAt method because it requires cloning error shown below.

I am able to POST HttpStringContent to the same web service and receive the responses without any issue.

The issue is when trying to send a file to the web service using HttpStreamContent.

public async void Upload_FileAsync(string WebServiceURL, string FilePathToUpload)
{

    //prepare HttpStreamContent
    IStorageFile storageFile = await StorageFile.GetFileFromPathAsync(FilePathToUpload);
    IBuffer buffer = await FileIO.ReadBufferAsync(storageFile);
    byte[] bytes = System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions.ToArray(buffer);
    Stream stream = new MemoryStream(bytes);
    Windows.Web.Http.HttpStreamContent streamContent = new Windows.Web.Http.HttpStreamContent(stream.AsInputStream());


    //send request
    var myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
    myFilter.AllowUI = false;
    var client = new Windows.Web.Http.HttpClient(myFilter);
    Windows.Web.Http.HttpResponseMessage result = await client.PostAsync(new Uri(WebServiceURL), streamContent);
    string stringReadResult = await result.Content.ReadAsStringAsync();

}

Full Error:

{System.NotSupportedException: This IRandomAccessStream does not support the GetInputStreamAt method because it requires cloning and this stream does not support cloning. at System.IO.NetFxToWinRtStreamAdapter.ThrowCloningNotSuported(String methodName) at System.IO.NetFxToWinRtStreamAdapter.GetInputStreamAt(UInt64 position) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at }

Please help!

After you get the file and begin to create a HttpStreamContent instance, you can try to use the StorageFile.OpenAsync method to get an IRandomAccessStream object, then put it as the HttpStreamContent object constructor parameter.

The code will be like this, you can have a try.

public async void Upload_FileAsync(string WebServiceURL, string FilePathToUpload)
{

    //prepare HttpStreamContent
    IStorageFile storageFile = await StorageFile.GetFileFromPathAsync(FilePathToUpload);

    //Here is the code we changed
    IRandomAccessStream stream=await storageFile.OpenAsync(FileAccessMode.Read);
    Windows.Web.Http.HttpStreamContent streamContent = new Windows.Web.Http.HttpStreamContent(stream);

    //send request
    var myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
    myFilter.AllowUI = false;
    var client = new Windows.Web.Http.HttpClient(myFilter);
    Windows.Web.Http.HttpResponseMessage result = await client.PostAsync(new Uri(WebServiceURL), streamContent);
    string stringReadResult = await result.Content.ReadAsStringAsync();
}


    선택기를 사용하여 파일 및 폴더 열기

    [ Windows 10의 UWP 앱에 맞게 업데이트되었습니다. Windows 8.x 문서는 보관을 참조하세요. ]

    중요 API

    사용자가 선택기를 조작할 수 있도록 하여 파일 및 폴더에 액세스합니다. FileOpenPicker 및 FileSavePicker 클래스를 사용하여 파일에 액세스하고 FolderPicker 클래스를 사용하여 폴더에 액세스할 수 있습니다.

    참고 전체 샘플에 대해서는 파일 선택기 샘플을 참조하세요.

    필수 조건

    파일 선택기 UI

    파일 선택기는 사용자를 안내하고 파일을 열거나 저장할 때 일관된 환경을 제공하기 위해 정보를 표시합니다.

    이러한 정보에는 다음이 포함됩니다.

    • 현재 위치
    • 사용자가 선택한 항목
    • 사용자가 이동할 수 있는 위치의 트리. 이러한 위치에는 파일 시스템 위치(예: 음악 또는 다운로드 폴더) 파일 선택기 계약을 구현하는 앱(예: 카메라, 사진 및 Microsoft OneDrive)이 포함됩니다.

    메일 앱은 사용자가 첨부 파일을 선택할 수 있도록 파일 선택기를 표시할 수 있습니다.

    두 개의 파일이 열기 위해 선택되어 있는 파일 선택기

    선택기 작동 방식

    선택기를 통해 앱은 사용자 시스템의 파일 및 폴더를 액세스하고 찾아보고 저장할 수 있습니다. 앱은 사용자가 작업할 수 있도록 StorageFile 및 StorageFolder 개체로 이러한 선택을 수신합니다.

    선택기는 통합된 단일 인터페이스를 사용하여 사용자가 파일 시스템이나 다른 앱에서 파일 및 폴더를 선택할 수 있도록 합니다. 다른 앱에서 선택한 파일은 파일 시스템의 파일과 유사하며 StorageFile 개체로 반환됩니다. 일반적으로 앱은 다른 개체와 동일한 방식으로 해당 개체에서 작동할 수 있습니다. 다른 앱에서는 파일 선택기 계약에 참여함으로써 파일을 사용할 수 있게 합니다. 앱에서 다른 앱에 파일, 저장 위치 또는 파일 업데이트를 제공하도록 하려면 파일 선택기 계약과 통합을 참조하세요.

    예를 들어 사용자가 파일을 열 수 있도록 앱에서 파일 선택기를 호출할 수 있습니다. 그러면 해당 앱이 호출 앱이 됩니다. 파일 선택기는 시스템 및/또는 다른 앱과 상호 작용하여 사용자가 파일을 탐색하고 선택할 수 있도록 합니다. 사용자가 파일을 선택하면 파일 선택기는 해당 파일을 앱에 반환합니다. 사용자가 OneDrive와 같은 제공 앱에서 파일을 선택할 경우의 프로세스는 다음과 같습니다.

    한 앱이 파일 선택기를 두 앱 간의 인터페이스로 사용하여 다른 앱에서 열 파일을 가져오는 프로세스를 보여 주는 다이어그램입니다.

    단일 파일 선택: 전체 코드 목록

    CSharp
    var picker = new Windows.Storage.Pickers.FileOpenPicker();
    picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
    picker.SuggestedStartLocation =
        Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
    picker.FileTypeFilter.Add(".jpg");
    picker.FileTypeFilter.Add(".jpeg");
    picker.FileTypeFilter.Add(".png");
    
    Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
    if (file != null)
    {
        // Application now has read/write access to the picked file
        this.textBlock.Text = "Picked photo: " + file.Name;
    }
    else
    {
        this.textBlock.Text = "Operation cancelled.";
    }
    

    단일 파일 선택: 단계별

    파일 선택기 사용에는 파일 선택기 개체를 만들고 사용자 지정한 다음 사용자가 하나 이상의 항목을 선택할 수 있도록 파일 선택기를 표시하는 과정이 포함됩니다.

    1. FileOpenPicker 만들기 및 사용자 지정

      CSharp
      var picker = new Windows.Storage.Pickers.FileOpenPicker();
          picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
          picker.SuggestedStartLocation =
              Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
          picker.FileTypeFilter.Add(".jpg");
          picker.FileTypeFilter.Add(".jpeg");
          picker.FileTypeFilter.Add(".png");
      

      사용자 및 앱과 관련된 파일 선택기 개체에서 속성을 설정합니다. 파일 선택기 사용자 지정 방법을 결정하는 데 도움이 되는 지침은 파일 선택기에 대한 지침 및 검사 목록을 참조하세요.

      이 예제에서는 세 가지 속성(ViewMode, SuggestedStartLocation  FileTypeFilter)을 설정하여 사용자가 선택할 수 있는 편리한 위치에 사진의 풍부한 시각적 표시를 만듭니다.

      • ViewMode PickerViewMode Thumbnail 열거 값으로 설정하면 사진 미리 보기를 사용하여 파일 선택기에 파일을 표시함으로써 풍부한 시각적 표시가 만들어집니다. 이렇게 하려면 사진이나 비디오와 같은 시각적 파일을 선택합니다. 그렇지 않으면 PickerViewMode.List를 사용합니다. 사진 또는 비디오 첨부  문서 첨부 기능이 있는 가상 메일 앱은 파일 선택기를 표시하기 전에 기능에 적합한 ViewMode를 설정합니다.

      • PickerLocationId.PicturesLibrary를 사용하여 SuggestedStartLocation을 사진으로 설정하면 사용자가 사진을 찾을 수 있을 것 같은 위치에서 시작됩니다. SuggestedStartLocation을 선택하려는 파일 형식(예: 음악, 사진, 동영상 또는 문서)에 적절한 위치로 설정합니다. 사용자는 시작 위치에서 다른 위치로 이동할 수 있습니다.

      • FileTypeFilter를 사용하여 파일 형식을 지정하면 사용자가 관련 있는 파일을 선택하는 데 집중할 수 있습니다. FileTypeFilter의 이전 파일 형식을 새 항목으로 대체하려면 Add 대신 ReplaceAll을 사용합니다.

    2. FileOpenPicker 표시

      • 단일 파일을 선택하려면
      CSharp
      Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
              if (file != null)
              {
                  // Application now has read/write access to the picked file
                  this.textBlock.Text = "Picked photo: " + file.Name;
              }
              else
              {
                  this.textBlock.Text = "Operation cancelled.";
              }
      
      • 여러 파일을 선택하려면
      CSharp
      var files = await picker.PickMultipleFilesAsync();
              if (files.Count > 0)
              {
                  StringBuilder output = new StringBuilder("Picked files:\n");
      
                  // Application now has read/write access to the picked file(s)
                  foreach (Windows.Storage.StorageFile file in files)
                  {
                      output.Append(file.Name + "\n");
                  }
                  this.textBlock.Text = output.ToString();
              }
              else
              {
                  this.textBlock.Text = "Operation cancelled.";
              }
      

    폴더 선택: 전체 코드 목록

    CSharp
    var folderPicker = new Windows.Storage.Pickers.FolderPicker();
    folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
    folderPicker.FileTypeFilter.Add("*");
    
    Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync();
    if (folder != null)
    {
        // Application now has read/write access to all contents in the picked folder
        // (including other sub-folder contents)
        Windows.Storage.AccessCache.StorageApplicationPermissions.
        FutureAccessList.AddOrReplace("PickedFolderToken", folder);
        this.textBlock.Text = "Picked folder: " + folder.Name;
    }
    else
    {
        this.textBlock.Text = "Operation cancelled.";
    }
    

     앱이 선택기를 통해 파일 또는 폴더에 액세스할 경우 해당 항목을 앱의 FutureAccessList 또는 MostRecentlyUsedList에 추가하여 추적합니다. 이러한 목록을 사용하는 방법에 대한 자세한 내용은 최근에 사용한 파일 및 폴더를 추적하는 방법을 참조하세요.

    파일 만들기, 쓰기 및 읽기

    [ Windows 10의 UWP 앱에 맞게 업데이트되었습니다. Windows 8.x 문서는 보관을 참조하세요. ]

    중요 API

    StorageFile 개체를 사용하여 파일을 읽고 씁니다.

    참고

    파일 액세스 샘플도 참조하세요.

    필수 조건

    파일 만들기

    앱의 로컬 폴더에 파일을 만드는 방법은 다음과 같습니다. 이미 있는 경우 바꿉니다.

    C#
    // Create sample file; replace if exists.
    Windows.Storage.StorageFolder storageFolder =
        Windows.Storage.ApplicationData.Current.LocalFolder;
    Windows.Storage.StorageFile sampleFile =
        await storageFolder.CreateFileAsync("sample.txt",
            Windows.Storage.CreationCollisionOption.ReplaceExisting);
    
    C++
    // Create a sample file; replace if exists.
    StorageFolder^ storageFolder = ApplicationData::Current->LocalFolder;
    concurrency::create_task(storageFolder->CreateFileAsync("sample.txt", CreationCollisionOption::ReplaceExisting));
    
    VB
    ' Create sample file; replace if exists.
    Dim storageFolder As StorageFolder = Windows.Storage.ApplicationData.Current.LocalFolder
    Dim sampleFile As StorageFile = Await storageFolder.CreateFileAsync("sample.txt", CreationCollisionOption.ReplaceExisting)
    

    파일에 쓰기

    StorageFile 클래스를 사용하여 디스크의 쓰기 가능 파일에 쓰는 방법은 다음과 같습니다. 파일에 쓰는 각 방법의 공통적인 첫 번째 단계(파일을 만든 즉시 해당 파일에 쓰는 경우 제외)는 StorageFolder.GetFileAsync를 사용하여 파일을 가져오는 것입니다.

    C#
    Windows.Storage.StorageFolder storageFolder =
        Windows.Storage.ApplicationData.Current.LocalFolder;
    Windows.Storage.StorageFile sampleFile =
        await storageFolder.GetFileAsync("sample.txt");
    
    C++
    StorageFolder^ storageFolder = ApplicationData::Current->LocalFolder;
    create_task(storageFolder->GetFileAsync("sample.txt")).then([](StorageFile^ sampleFile) 
    {
        // Process file
    });
    
    VB
    Dim storageFolder As StorageFolder = Windows.Storage.ApplicationData.Current.LocalFolder
    Dim sampleFile As StorageFile = Await storageFolder.GetFileAsync("sample.txt")
    

    파일에 텍스트 쓰기

    FileIO 클래스의 WriteTextAsync 메서드를 호출하여 파일에 텍스트를 씁니다.

    C#
    await Windows.Storage.FileIO.WriteTextAsync(sampleFile, "Swift as a shadow");
    
    C++
    StorageFolder^ storageFolder = ApplicationData::Current->LocalFolder;
    create_task(storageFolder->GetFileAsync("sample.txt")).then([](StorageFile^ sampleFile) 
    {
        //Write text to a file
        create_task(FileIO::WriteTextAsync(sampleFile, "Swift as a shadow"));
    });
    
    VB
    Await Windows.Storage.FileIO.WriteTextAsync(sampleFile, "Swift as a shadow")
    

    버퍼를 사용하여 파일에 바이트 쓰기(2단계)

    1. 먼저 ConvertStringToBinary를 호출하여 파일에 쓰려는 바이트(임의 문자열 기반)의 버퍼를 가져옵니다.

      C#
      var buffer = Windows.Security.Cryptography.CryptographicBuffer.ConvertStringToBinary(
              "What fools these mortals be", Windows.Security.Cryptography.BinaryStringEncoding.Utf8);
      
      C++
      StorageFolder^ storageFolder = ApplicationData::Current->LocalFolder;
      create_task(storageFolder->GetFileAsync("sample.txt")).then([](StorageFile^ sampleFile)
      {
          // Create the buffer
          IBuffer^ buffer = CryptographicBuffer::ConvertStringToBinary
          ("What fools these mortals be", BinaryStringEncoding::Utf8);
      });
      
      VB
      Dim buffer = Windows.Security.Cryptography.CryptographicBuffer.ConvertStringToBinary(
                          "What fools these mortals be",
                          Windows.Security.Cryptography.BinaryStringEncoding.Utf8)
      
    2. 그런 다음 FileIO 클래스의 WriteBufferAsync 메서드를 호출하여 파일에 버퍼의 바이트를 씁니다.

      C#
      await Windows.Storage.FileIO.WriteBufferAsync(sampleFile, buffer);
      
      C++
      StorageFolder^ storageFolder = ApplicationData::Current->LocalFolder;
      create_task(storageFolder->GetFileAsync("sample.txt")).then([](StorageFile^ sampleFile)
      {
          // Create the buffer
          IBuffer^ buffer = CryptographicBuffer::ConvertStringToBinary
          ("What fools these mortals be", BinaryStringEncoding::Utf8);      
          // Write bytes to a file using a buffer
          create_task(FileIO::WriteBufferAsync(sampleFile, buffer));
      });
      
      VB
      Await Windows.Storage.FileIO.WriteBufferAsync(sampleFile, buffer)
      

    스트림을 사용하여 파일에 텍스트 쓰기(4단계)

    1. 먼저 StorageFile.OpenAsync 메서드를 호출하여 파일을 엽니다. 이 메서드는 열기 작업이 완료되면 파일 내용의 스트림을 반환합니다.

      C#
      var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
      
      C++
      StorageFolder^ storageFolder = ApplicationData::Current->LocalFolder;
      create_task(storageFolder->GetFileAsync("sample.txt")).then([](StorageFile^ sampleFile)
      {
          create_task(sampleFile->OpenAsync(FileAccessMode::ReadWrite)).then([sampleFile](IRandomAccessStream^ stream)
          {
              // Process stream
          });
      });
      
      VB
      Dim stream = Await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite)
      
    2. 다음으로, stream에서 GetOutputStreamAt 메서드를 호출하여 출력 스트림을 가져옵니다. using 문에 이 스트림을 넣어 출력 스트림의 수명을 관리합니다.

      C#
      using (var outputStream = stream.GetOutputStreamAt(0))
      {
          // We'll add more code here in the next step.
      }
      stream.Dispose(); // Or use the stream variable (see previous code snippet) with a using statement as well.
      
      C++
      // Add to "Process stream" in part 1
      IOutputStream^ outputStream = stream->GetOutputStreamAt(0);
      
      VB
      Using outputStream = stream.GetOutputStreamAt(0)
      ' We'll add more code here in the next step.
      End Using
      
    3. 이제 기존 using 문 내에 다음 코드를 추가해 새 DataWriter 개체를 만들고 DataWriter.WriteString 메서드를 호출하여 출력 스트림에 씁니다.

      C#
      using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
      {
          dataWriter.WriteString("DataWriter has methods to write to various types, such as DataTimeOffset.");
      }
      
      C++
      // Added after code from part 2
      DataWriter^ dataWriter = ref new DataWriter(outputStream);
      dataWriter->WriteString("DataWriter has methods to write to various types, such as DataTimeOffset.");
      
      VB
      Dim dataWriter As New DataWriter(outputStream)
      dataWriter.WriteString("DataWriter has methods to write to various types, such as DataTimeOffset.")
      
    4. 마지막으로, 내부 using 문 내에 다음 코드를 추가하여 StoreAsync로 텍스트를 파일에 저장하고 FlushAsync로 스트림을 닫습니다.

      C#
      await dataWriter.StoreAsync();
          await outputStream.FlushAsync();
      
      C++
      // Added after code from part 3
      dataWriter->StoreAsync();
      outputStream->FlushAsync();
      
      VB
      Await dataWriter.StoreAsync()
          Await outputStream.FlushAsync()
      

    파일에서 읽기

    StorageFile 클래스를 사용하여 디스크의 파일에서 읽는 방법은 다음과 같습니다. 파일에서 읽는 각 방법의 공통적인 첫 번째 단계는 StorageFolder.GetFileAsync를 사용하여 파일을 가져오는 것입니다.

    C#
    Windows.Storage.StorageFolder storageFolder =
        Windows.Storage.ApplicationData.Current.LocalFolder;
    Windows.Storage.StorageFile sampleFile =
        await storageFolder.GetFileAsync("sample.txt");
    
    C++
    StorageFolder^ storageFolder = ApplicationData::Current->LocalFolder;
    create_task(storageFolder->GetFileAsync("sample.txt")).then([](StorageFile^ sampleFile)
    {
        // Process file
    });
    
    VB
    Dim storageFolder As StorageFolder = Windows.Storage.ApplicationData.Current.LocalFolder
    Dim sampleFile As StorageFile = Await storageFolder.GetFileAsync("sample.txt")
    

    파일에서 텍스트 읽기

    FileIO 클래스의 ReadTextAsync 메서드를 호출하여 파일에서 텍스트를 읽습니다.

    C#
    string text = await Windows.Storage.FileIO.ReadTextAsync(sampleFile);
    
    C++
    StorageFolder^ storageFolder = ApplicationData::Current->LocalFolder;
    create_task(storageFolder->GetFileAsync("sample.txt")).then([](StorageFile^ sampleFile)
    {
        return FileIO::ReadTextAsync(sampleFile);
    });
    
    VB
    Dim text As String = Await Windows.Storage.FileIO.ReadTextAsync(sampleFile)
    

    버퍼를 사용하여 파일에서 텍스트 읽기(2단계)

    1. 먼저 FileIO 클래스의 ReadBufferAsync 메서드를 호출합니다.

      C#
      var buffer = await Windows.Storage.FileIO.ReadBufferAsync(sampleFile);
      
      C++
      StorageFolder^ storageFolder = ApplicationData::Current->LocalFolder;
      create_task(storageFolder->GetFileAsync("sample.txt")).then([](StorageFile^ sampleFile)
      {
          return FileIO::ReadBufferAsync(sampleFile);
      
      }).then([](Streams::IBuffer^ buffer)
      {
          // Process buffer
      });
      
      VB
      Dim buffer = Await Windows.Storage.FileIO.ReadBufferAsync(sampleFile)
      
    2. 그런 다음 DataReader 개체를 사용하여 버퍼의 길이와 버퍼의 내용을 차례로 읽습니다.

      C#
      using (var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(buffer))
      {
          string text = dataReader.ReadString(buffer.Length);
      }
      
      C++
      // Add to "Process buffer" section from part 1
      auto dataReader = DataReader::FromBuffer(buffer);
      String^ bufferText = dataReader->ReadString(buffer->Length);
      
      VB
      Dim dataReader As DataReader = Windows.Storage.Streams.DataReader.FromBuffer(buffer)
      Dim text As String = dataReader.ReadString(buffer.Length)
      

    스트림을 사용하여 파일에서 텍스트 읽기(4단계)

    1. StorageFile.OpenAsync 메서드를 호출하여 파일의 스트림을 엽니다. 이 메서드는 작업이 완료되면 파일 내용의 스트림을 반환합니다.

      C#
      var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
      
      C++
      StorageFolder^ storageFolder = ApplicationData::Current->LocalFolder;
      create_task(storageFolder->GetFileAsync("sample.txt")).then([](StorageFile^ sampleFile)
      {
          create_task(sampleFile->OpenAsync(FileAccessMode::Read)).then([sampleFile](IRandomAccessStream^ stream)
          {
              // Process stream
          });
      });
      
      VB
      Dim stream = Await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.Read)
      
    2. 나중에 사용할 스트림의 크기를 가져옵니다.

      C#
      ulong size = stream.Size;
      
      C++
      // Add to "Process stream" from part 1
      UINT64 size = stream->Size;
      
      VB
      Dim size = stream.Size
      
    3. GetInputStreamAt 메서드를 호출하여 입력 스트림을 가져옵니다. 이를 using 문에 배치하여 스트림의 수명을 관리합니다. GetInputStreamAt을 호출할 때 0을 지정하여 위치를 스트림의 시작 부분으로 설정합니다.

      C#
      using (var inputStream = stream.GetInputStreamAt(0))
      {
          // We'll add more code here in the next step.
      }
      
      C++
      // Add after code from part 2
      IInputStream^ inputStream = stream->GetInputStreamAt(0);
      auto dataReader = ref new DataReader(inputStream);
      
      VB
      Using inputStream = stream.GetInputStreamAt(0)
          ' We'll add more code here in the next step.
      End Using
      
    4. 마지막으로, 기존 using 문 내에 다음 코드를 추가하여 스트림에서 DataReader 개체를 가져온 다음 DataReader.LoadAsync  DataReader.ReadString를 호출하여 텍스트를 읽습니다.

      C#
      using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream))
      {
          uint numBytesLoaded = await dataReader.LoadAsync((uint)size);
          string text = dataReader.ReadString(numBytesLoaded);
      }
      
      C++
      // Add after code from part 3
      create_task(dataReader->LoadAsync(size)).then([sampleFile, dataReader](unsigned int numBytesLoaded)
      {
          String^ streamText = dataReader->ReadString(numBytesLoaded);
      });
      
      VB
      Dim dataReader As New DataReader(inputStream)
      Dim numBytesLoaded As UInteger = Await dataReader.LoadAsync(CUInt(size))
      Dim text As String = dataReader.ReadString(numBytesLoaded)


    + Recent posts