このエントリーをはてなブックマークに追加


StreamReaderを使ったテキストファイルの読み込み

StreamReaderを使ったテキストファイルの読み込みのサンプルコードを紹介します。

参考サイト

StreamReaderでテキストファイルを読込

C#、Visual Basic(VB)でStreamReaderを使ったサンプルコードになります。

関連記事

C#サンプルコード

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);
        }
    }
}

Visual Basic(VB)サンプルコード

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を使ったサンプルコードを実行した時のキャプチャになります。

01.png

以上、StreamReader使ってテキストファイルを読み込むサンプルコードでした。


添付ファイル: file01.png 143件 [詳細]

トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2019-12-08 (日) 16:17:17