StreamReaderを使ったテキストファイルの読み込みのサンプルコードを紹介します。
C#、Visual Basic(VB)でStreamReaderを使ったサンプルコードになります。
using System;
class Program
{
static void Main(string[] args)
{
String hosts = @"C:\Windows\System32\drivers\etc\hosts";
try
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(hosts))
{
String l;
while ((l = sr.ReadLine()) != null)
{
Console.WriteLine(l);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
Module Module1
Sub Main()
Dim hosts As String = "C:\Windows\System32\drivers\etc\hosts"
Try
Using sr As System.IO.StreamReader = New System.IO.StreamReader(hosts)
Dim l As String
Do
l = sr.ReadLine()
Console.WriteLine(l)
Loop Until l Is Nothing
End Using
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
End Module
以下にStreamReaderを使ったサンプルコードを実行した時のキャプチャになります。
以上、StreamReader使ってテキストファイルを読み込むサンプルコードでした。