方法: ファイルのテキストの読み取り
次に、.NET デスクトップ アプリを使用してテキスト ファイルから同期でテキストを読み取る方法と非同期でテキストを読み取る方法の例を示します。 どちらの例でも、StreamReader クラスのインスタンスを作成する場合に、ファイルの相対パスまたは絶対パスを指定します。
Note
Windows ランタイムではファイルに対する読み取りと書き込みに別のストリーム型が用意されているため、これらのコード例はユニバーサル Windows プラットフォーム (UWP) アプリには適用されません。 UWP アプリのファイルからテキストを読み取る方法を示す例については、「Quickstart: Reading and writing files」 (クイック スタート: ファイルの読み取りと書き込み) を参照してください。 .NET Framework ストリームと Windows ランタイム ストリーム間で変換を行う方法を示す例については、「方法: .NET Framework ストリームと Windows ランタイム ストリームの間で変換を行う」を参照してください。
例:コンソール アプリの同期読み取り
次の例では、コンソール アプリ内での同期読み取り操作を示します。 この例では、ストリーム リーダーを使用してテキスト ファイルを開き、コンテンツが文字列にコピーされ、文字列がコンソールに出力されます。
重要
サンプルでは、TestFile.txt という名前のファイルがアプリと同じフォルダーに入っていると想定しています。
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
例:WPF アプリの非同期読み取り
次の例では、Windows Presentation Foundation (WPF) アプリ内での非同期読み取り操作を示します。
重要
サンプルでは、TestFile.txt という名前のファイルがアプリと同じフォルダーに入っていると想定しています。
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