Procedura: Leggere testo da un file

Negli esempi seguenti viene illustrato come leggere il testo in modo sincrono e in modo asincrono da un file di testo usando .NET per le applicazioni desktop. In entrambi gli esempi, quando si crea l'istanza della classe StreamReader, si immette il percorso relativo o assoluto del file.

Nota

Questi esempi di codice non si applicano alle app UWP (Universal Windows), perché Windows Runtime fornisce diversi tipi di flusso per la lettura e la scrittura nei file. Per un esempio che illustra come leggere il testo da un file in un'app UWP, vedere Avvio rapido: Lettura e scrittura di file. Per esempi che illustrano come convertire tra flussi .NET Framework e flussi di Windows Runtime, vedere Procedura: Convertire tra flussi .NET Framework e flussi Windows Runtime.

Esempio: lettura sincrona in un'app console

L'esempio seguente mostra un'operazione di lettura sincrona in un'app console. In questo esempio viene aperto il file di testo usando un lettore di flusso, il contenuto viene copiato in una stringa e la stringa viene quindi restituita nella console.

Importante

L'esempio presuppone che un file denominato TestFile.txt esista già nella stessa cartella dell'app.

using System;
using System.IO;

class Program
{
    public static void Main()
    {
        try
        {
            // Open the text file using a stream reader.
            using (var sr = new StreamReader("TestFile.txt"))
            {
                // Read the stream as a string, and write the string to the console.
                Console.WriteLine(sr.ReadToEnd());
            }
        }
        catch (IOException e)
        {
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }
    }
}
Imports System.IO

Module Program
    Public Sub Main()
        Try
            ' Open the file using a stream reader.
            Using sr As New StreamReader("TestFile.txt")
                ' Read the stream as a string and write the string to the console.
                Console.WriteLine(sr.ReadToEnd())
            End Using
        Catch e As IOException
            Console.WriteLine("The file could not be read:")
            Console.WriteLine(e.Message)
        End Try
    End Sub
End Module

Esempio: Lettura asincrona in un'app WPF

L'esempio seguente illustra un'operazione di lettura asincrona in un'app Windows Presentation Foundation (WPF).

Importante

L'esempio presuppone che un file denominato TestFile.txt esista già nella stessa cartella dell'app.

using System.IO;
using System.Windows;

namespace TextFiles;

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow() => InitializeComponent();

    private async void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        try
        {
            using (var sr = new StreamReader("TestFile.txt"))
            {
                ResultBlock.Text = await sr.ReadToEndAsync();
            }
        }
        catch (FileNotFoundException ex)
        {
            ResultBlock.Text = ex.Message;
        }
    }
}
Imports System.IO
Imports System.Windows

''' <summary>
''' Interaction logic for MainWindow.xaml
''' </summary>

Partial Public Class MainWindow
    Inherits Window
    Public Sub New()
        InitializeComponent()
    End Sub

    Private Async Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs)
        Try
            Using sr As New StreamReader("TestFile.txt")
                ResultBlock.Text = Await sr.ReadToEndAsync()
            End Using
        Catch ex As FileNotFoundException
            ResultBlock.Text = ex.Message
        End Try
    End Sub
End Class

Vedi anche