パソコンの小技・備忘録


トップページ > 小技一覧(VB.NET) > テキストファイルを読み込む。

テキストファイルを読み込む。

テキストファイルを読み込む場合は、下記のように記述します。

'Dドライブの直下にある「test.txt」を開く場合
Dim srText As New System.IO.StreamReader("D:\text.txt", _
         System.Text.Encoding.GetEncoding(932))

'読み込むための変数を定義し、テキストファイルを読み込む
Dim strText As String
strText = srText.ReadToEnd()

'読み込んだ時点で、テキストファイルを占有する必要がなくなるので、
'解放する。
srText.Dispose()

'変数に取得したテキストを任意の方法で出力する。
'下記では、TextBox1に表示する。
Me.TextBox1.Text = strText

この例では、Shift-JISで読み込んでいますが、Encodingの記述を変更することで、他の文字コードとして読み込むことも可能です。

'Shift-JISを文字で指定
Dim srText As New System.IO.StreamReader("D:\text.txt", _
         System.Text.Encoding.GetEncoding("shift-jis"))

'Shift-JISをコードページで指定(これが上記の例です。)
Dim srText As New System.IO.StreamReader("D:\text.txt", _
         System.Text.Encoding.GetEncoding(932))

'UTF-8を文字で指定
Dim srText As New System.IO.StreamReader("D:\text.txt", _
         System.Text.Encoding.GetEncoding("utf-8"))

'UTF-8をコードページで指定(これが上記の例です。)
Dim srText As New System.IO.StreamReader("D:\text.txt", _
         System.Text.Encoding.GetEncoding(65001))

'EUCを文字で指定
Dim srText As New System.IO.StreamReader("D:\text.txt", _
         System.Text.Encoding.GetEncoding("euc-jp"))

'EUCをコードページで指定(これが上記の例です。)
Dim srText As New System.IO.StreamReader("D:\text.txt", _
         System.Text.Encoding.GetEncoding(51932))

文字コードは、他にもいろいろありますが、管理人は上記くらいしか使いません。

諸事情で、他の文字コードとかを使う方は、MSDNなどで「Encoding」などをキーワードにして探してみてください。

トップページに戻る

パソコンの小技・備忘録トップページ(http://pckowaza.web.fc2.com/)を表示

※更新履歴などを掲載していますので、お気に入りはぜひトップページでお願いします!

サイト内検索

 Googleでサイト内検索

小技カテゴリー

カウンタ

メール送信

 ご意見・相互リンク募集中!
意見・相互リンクメールを送信!
inserted by FC2 system