WindowsRuntimeStorageExtensions.OpenStreamForReadAsync Méthode
Définition
Important
Certaines informations portent sur la préversion du produit qui est susceptible d’être en grande partie modifiée avant sa publication. Microsoft exclut toute garantie, expresse ou implicite, concernant les informations fournies ici.
Surcharges
| Nom | Description |
|---|---|
| OpenStreamForReadAsync(IStorageFile) |
Récupère un flux de lecture à partir d’un fichier spécifié. |
| OpenStreamForReadAsync(IStorageFolder, String) |
Récupère un flux de lecture à partir d’un fichier dans le dossier parent spécifié. |
OpenStreamForReadAsync(IStorageFile)
Important
Cette API n’est pas conforme CLS.
Récupère un flux de lecture à partir d’un fichier spécifié.
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)
Paramètres
- windowsRuntimeFile
- Windows.Storage.IStorageFile
Objet Windows Runtime Windows.Storage.IStorageFile à lire.
Retours
Tâche qui représente l’opération de lecture asynchrone.
- Attributs
Exceptions
windowsRuntimeFile a la valeur null.
Le fichier n’a pas pu être ouvert ou récupéré en tant que flux.
Exemples
L’exemple suivant montre comment ouvrir un fichier en tant que Stream dans une application Windows Store et lire son contenu à l’aide d’une instance de la classe 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
L’exemple suivant montre le code XAML associé à l’exemple précédent.
<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>
Remarques
Note
Dans Visual Basic et C#, vous pouvez appeler cette méthode en tant que méthode d’instance sur n’importe quel objet de type <xref:Windows.Storage.IStorageFile>. Lorsque vous utilisez la syntaxe de méthode d’instance pour appeler cette méthode, omettez le premier paramètre. Pour plus d’informations, consultez Extension Methods (Visual Basic) ou Extension Methods (C# Programming Guide).
S’applique à
OpenStreamForReadAsync(IStorageFolder, String)
Important
Cette API n’est pas conforme CLS.
Récupère un flux de lecture à partir d’un fichier dans le dossier parent spécifié.
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)
Paramètres
- rootDirectory
- Windows.Storage.IStorageFolder
Objet Windows Runtime Windows.Storage.IStorageFile qui contient le fichier à lire.
- relativePath
- String
Chemin d’accès, relatif au dossier racine, au fichier à partir duquel lire.
Retours
Tâche qui représente l’opération de lecture asynchrone.
- Attributs
Exceptions
rootDirectory ou relativePath est null.
relativePath est vide ou contient uniquement des espaces blancs.
Le fichier n’a pas pu être ouvert ou récupéré en tant que flux.
Exemples
L’exemple suivant montre comment ouvrir un fichier en tant que Stream dans une application Windows Store et lire son contenu à l’aide d’une instance de la classe 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
L’exemple suivant montre le code XAML associé à l’exemple précédent.
<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>
Remarques
Note
Dans Visual Basic et C#, vous pouvez appeler cette méthode en tant que méthode d’instance sur n’importe quel objet de type IStorageFolder. Lorsque vous utilisez la syntaxe de méthode d’instance pour appeler cette méthode, omettez le premier paramètre. Pour plus d’informations, consultez Extension Methods (Visual Basic) ou Extension Methods (C# Programming Guide).