WindowsRuntimeStorageExtensions.OpenStreamForReadAsync 메서드

정의

오버로드

OpenStreamForReadAsync(IStorageFile)

지정된 파일에서 읽기 위한 스트림을 검색합니다.

OpenStreamForReadAsync(IStorageFolder, String)

지정한 상위 폴더의 파일에서 읽기 위한 스트림을 검색합니다.

OpenStreamForReadAsync(IStorageFile)

중요

이 API는 CLS 규격이 아닙니다.

지정된 파일에서 읽기 위한 스트림을 검색합니다.

public:
[System::Runtime::CompilerServices::Extension]
 static System::Threading::Tasks::Task<System::IO::Stream ^> ^ OpenStreamForReadAsync(Windows::Storage::IStorageFile ^ windowsRuntimeFile);
[System.CLSCompliant(false)]
public static System.Threading.Tasks.Task<System.IO.Stream> OpenStreamForReadAsync (this Windows.Storage.IStorageFile windowsRuntimeFile);
[<System.CLSCompliant(false)>]
static member OpenStreamForReadAsync : Windows.Storage.IStorageFile -> System.Threading.Tasks.Task<System.IO.Stream>
<Extension()>
Public Function OpenStreamForReadAsync (windowsRuntimeFile As IStorageFile) As Task(Of Stream)

매개 변수

windowsRuntimeFile
IStorageFile

읽을 Windows 런타임 IStorageFile 개체입니다.

반환

비동기 읽기 작업을 나타내는 작업입니다.

특성

예외

windowsRuntimeFile이(가) null인 경우

파일을 열 수 없거나 스트림으로 검색할 수 없습니다.

예제

다음 예제에서는 Windows 스토어 앱에서 으로 Stream 파일을 열고 클래스의 StreamReader 인스턴스를 사용하여 해당 내용을 읽는 방법을 보여 줍니다.

using System;
using System.IO;
using System.Text;
using Windows.Storage.Pickers;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace ExampleApplication
{
    public sealed partial class BlankPage : Page
    {
        public BlankPage()
        {
            this.InitializeComponent();
        }

        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            StringBuilder contents = new StringBuilder();
            string nextLine;
            int lineCounter = 1;

            var openPicker = new FileOpenPicker();
            openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            openPicker.FileTypeFilter.Add(".txt");
            StorageFile selectedFile = await openPicker.PickSingleFileAsync();

            using (StreamReader reader = new StreamReader(await selectedFile.OpenStreamForReadAsync()))
            {
                while ((nextLine = await reader.ReadLineAsync()) != null)
                {
                    contents.AppendFormat("{0}. ", lineCounter);
                    contents.Append(nextLine);
                    contents.AppendLine();
                    lineCounter++;
                    if (lineCounter > 3)
                    {
                        contents.AppendLine("Only first 3 lines shown.");
                        break;
                    }
                }
            }
            DisplayContentsBlock.Text = contents.ToString();
        }
    }
}
Imports System.Text
Imports System.IO
Imports Windows.Storage.Pickers
Imports Windows.Storage

NotInheritable Public Class BlankPage
    Inherits Page

    

    Private Async Sub Button_Click_1(sender As Object, e As RoutedEventArgs)
        Dim contents As StringBuilder = New StringBuilder()
        Dim nextLine As String
        Dim lineCounter As Integer = 1

        Dim openPicker = New FileOpenPicker()
        openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary

        openPicker.FileTypeFilter.Add(".txt")
        Dim selectedFile As StorageFile = Await openPicker.PickSingleFileAsync()

        Using reader As StreamReader = New StreamReader(Await selectedFile.OpenStreamForReadAsync())
            nextLine = Await reader.ReadLineAsync()
            While (nextLine <> Nothing)
                contents.AppendFormat("{0}. ", lineCounter)
                contents.Append(nextLine)
                contents.AppendLine()
                lineCounter = lineCounter + 1
                If (lineCounter > 3) Then
                    contents.AppendLine("Only first 3 lines shown.")
                    Exit While
                End If
                nextLine = Await reader.ReadLineAsync()
            End While
        End Using
        DisplayContentsBlock.Text = contents.ToString()
    End Sub
End Class

다음 예제에서는 이전 예제와 연결된 XAML 코드를 보여줍니다.

<Page
    x:Class="ExampleApplication.BlankPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:ExampleApplication"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <StackPanel Background="{StaticResource ApplicationPageBackgroundBrush}" VerticalAlignment="Center" HorizontalAlignment="Center">
        <TextBlock Text="Display lines from a file."></TextBlock>
        <Button Content="Load File" Click="Button_Click_1"></Button>
        <TextBlock Name="DisplayContentsBlock"></TextBlock>
    </StackPanel>
</Page>

설명

참고

Visual Basic 및 C#에서는 형식 IStorageFile의 모든 개체에서 이 메서드를 인스턴스 메서드로 호출할 수 있습니다. 인스턴스 메서드 구문을 사용하여 이 메서드를 호출할 경우에는 첫 번째 매개 변수를 생략합니다. 자세한 내용은 확장 메서드(Visual Basic) 또는 확장 메서드(C# 프로그래밍 가이드)를 참조하세요.

적용 대상

OpenStreamForReadAsync(IStorageFolder, String)

중요

이 API는 CLS 규격이 아닙니다.

지정한 상위 폴더의 파일에서 읽기 위한 스트림을 검색합니다.

public:
[System::Runtime::CompilerServices::Extension]
 static System::Threading::Tasks::Task<System::IO::Stream ^> ^ OpenStreamForReadAsync(Windows::Storage::IStorageFolder ^ rootDirectory, System::String ^ relativePath);
[System.CLSCompliant(false)]
public static System.Threading.Tasks.Task<System.IO.Stream> OpenStreamForReadAsync (this Windows.Storage.IStorageFolder rootDirectory, string relativePath);
[<System.CLSCompliant(false)>]
static member OpenStreamForReadAsync : Windows.Storage.IStorageFolder * string -> System.Threading.Tasks.Task<System.IO.Stream>
<Extension()>
Public Function OpenStreamForReadAsync (rootDirectory As IStorageFolder, relativePath As String) As Task(Of Stream)

매개 변수

rootDirectory
IStorageFolder

읽을 파일이 포함된 Windows 런타임 IStorageFile 개체입니다.

relativePath
String

읽을 파일의 경로(루트 폴더에 상대적)입니다.

반환

비동기 읽기 작업을 나타내는 작업입니다.

특성

예외

rootDirectory 또는 relativePathnull인 경우

relativePath이 비어 있거나 공백 문자만 있습니다.

파일을 열 수 없거나 스트림으로 검색할 수 없습니다.

예제

다음 예제에서는 Windows 스토어 앱에서 으로 Stream 파일을 열고 클래스의 StreamReader 인스턴스를 사용하여 해당 내용을 읽는 방법을 보여 줍니다.

using System;
using System.IO;
using Windows.Storage.Pickers;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace ExampleApplication
{
    public sealed partial class BlankPage : Page
    {
        public BlankPage()
        {
            this.InitializeComponent();
            CreateTestFile();
        }

        private async void CreateTestFile()
        {
            StorageFile newFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("testfile.txt");
            await FileIO.WriteTextAsync(newFile, "example content in file");
        }

        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            using (StreamReader reader = new StreamReader(
                await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync("testfile.txt")))
            {
                string contents = await reader.ReadToEndAsync();
                DisplayContentsBlock.Text = contents;
            }
        }
    }
}
Imports System.IO
Imports Windows.Storage

NotInheritable Public Class BlankPage
    Inherits Page

    Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)
        CreateTestFile()
    End Sub

    Private Async Sub CreateTestFile()
        Dim newFile As StorageFile = Await ApplicationData.Current.LocalFolder.CreateFileAsync("testfile.txt")
        Await FileIO.WriteTextAsync(newFile, "example content in file")
    End Sub

    Private Async Sub Button_Click_1(sender As Object, e As RoutedEventArgs)
        Using reader As StreamReader = New StreamReader(
                Await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync("testfile.txt"))

            Dim contents As String = Await reader.ReadToEndAsync()
            DisplayContentsBlock.Text = contents
        End Using
    End Sub
End Class

다음 예제에서는 이전 예제와 연결된 XAML 코드를 보여줍니다.

<Page
    x:Class="ExampleApplication.BlankPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:ExampleApplication"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <StackPanel Background="{StaticResource ApplicationPageBackgroundBrush}" VerticalAlignment="Center" HorizontalAlignment="Center">
        <Button Content="Open File" Click="Button_Click_1"></Button>
        <TextBlock Name="DisplayContentsBlock"></TextBlock>
    </StackPanel>
</Page>

설명

참고

Visual Basic 및 C#에서는 IStorageFolder 형식의 모든 개체에서 이 메서드를 인스턴스 메서드로 호출할 수 있습니다. 인스턴스 메서드 구문을 사용하여 이 메서드를 호출할 경우에는 첫 번째 매개 변수를 생략합니다. 자세한 내용은 확장 메서드(Visual Basic) 또는 확장 메서드(C# 프로그래밍 가이드)를 참조하세요.

적용 대상