WindowsRuntimeStorageExtensions.OpenStreamForReadAsync 方法

定义

重载

OpenStreamForReadAsync(IStorageFile)

检索流以从指定的文件中读取。Retrieves a stream for reading from a specified file.

OpenStreamForReadAsync(IStorageFolder, String)

检索流以从指定的父文件夹的一个文件中读取。Retrieves a stream for reading from a file in the specified parent folder.

OpenStreamForReadAsync(IStorageFile)

重要

此 API 不符合 CLS。

检索流以从指定的文件中读取。Retrieves a stream for reading from a specified file.

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 对象。The Windows Runtime IStorageFile object to read from.

返回

Task<Stream>

表示异步读取操作的任务。A task that represents the asynchronous read operation.

属性

例外

windowsRuntimeFilenullwindowsRuntimeFile is null.

无法以流的形式打开或检索文件。The file could not be opened or retrieved as a stream.

示例

下面的示例演示如何 Stream 在 Windows 应用商店应用程序中将文件作为打开,并通过使用类的实例来读取其内容 StreamReaderThe following example shows how to open a file as a Stream in a Windows Store app, and read its contents by using an instance of the StreamReader class.

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 代码。The next example shows the XAML code that is associated with the previous example.

<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 # 中,可以在类型为的任何对象上将此方法作为实例方法来调用 IStorageFileIn Visual Basic and C#, you can call this method as an instance method on any object of type IStorageFile. 当使用实例方法语法调用此方法时,请省略第一个参数。When you use instance method syntax to call this method, omit the first parameter. 有关详细信息,请参阅c # 编程指南) Visual Basic) 或 (扩展方法 (的扩展方法For more information, see Extension Methods (Visual Basic) or Extension Methods (C# Programming Guide).

适用于

OpenStreamForReadAsync(IStorageFolder, String)

重要

此 API 不符合 CLS。

检索流以从指定的父文件夹的一个文件中读取。Retrieves a stream for reading from a file in the specified parent folder.

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 对象。The Windows Runtime IStorageFile object that contains the file to read from.

relativePath
String

相对于根文件夹,到要读取的文件的路径。The path, relative to the root folder, to the file to read from.

返回

Task<Stream>

表示异步读取操作的任务。A task that represents the asynchronous read operation.

属性

例外

rootDirectoryrelativePathnullrootDirectory or relativePath is null.

relativePath 为空,或者只包含空白字符。relativePath is empty or contains only white-space characters.

无法以流的形式打开或检索文件。The file could not be opened or retrieved as a stream.

示例

下面的示例演示如何 Stream 在 Windows 应用商店应用程序中将文件作为打开,并通过使用类的实例来读取其内容 StreamReaderThe following example shows how to open a file as a Stream in a Windows Store app, and read its contents by using an instance of the StreamReader class.

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 代码。The next example shows the XAML code that is associated with the previous example.

<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 类型的任何对象上的实例方法来调用。In Visual Basic and C#, you can call this method as an instance method on any object of type IStorageFolder. 当使用实例方法语法调用此方法时,请省略第一个参数。When you use instance method syntax to call this method, omit the first parameter. 有关详细信息,请参阅c # 编程指南) Visual Basic) 或 (扩展方法 (的扩展方法For more information, see Extension Methods (Visual Basic) or Extension Methods (C# Programming Guide).

适用于