テキストファイルの読み書き

Readボタンを押すと、テキストファイルを読んでListBoxに表示します。また、ピクチャボックスにも表示します。Writeボタンを押すと、ListBoxの内容を、テキストファイルへ出力します。 フォーム1 Public … “テキストファイルの読み書き” の続きを読む

Readボタンを押すと、テキストファイルを読んでListBoxに表示します。また、ピクチャボックスにも表示します。
Writeボタンを押すと、ListBoxの内容を、テキストファイルへ出力します。

フォーム1

Public Class Form1

ボタン1


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

’ファイルIO用の変数等の宣言

Dim fname As String
Dim ret As DialogResult
Dim TextFile As IO.StreamReader
Dim Line As String
Dim cnt As Integer

’PictureBox1のGraphicsオブジェクトを取得

Dim g As Graphics = PictureBox1.CreateGraphics()
Dim ystr As Integer

‘ダイアログボックスの初期設定

With Me.OpenFileDialog1
 .Title = “ファイルを開く”
 .CheckFileExists = True
  .RestoreDirectory = True
 .Filter = “テキストファイル|.txt;.dat”
 .FileName = “test.txt”
End With

‘ダイアログボックスの表示

ret = Me.OpenFileDialog1.ShowDialog()
If ret = Windows.Forms.DialogResult.OK Then
 fname = Me.OpenFileDialog1.FileName
Else
 fname = “”
End If
If IO.File.Exists(fname) = False Then
 MessageBox.Show(“ファイルが見つかりません。”, “通知”)
 Exit Sub
End If

‘フォントオブジェクトの作成

Dim fnt As New Font(“MS UI Gothic”, 12)
Me.ListBox1.Items.Clear()
TextFile = New IO.StreamReader(fname, System.Text.Encoding.Default)

cnt = 0
Do While True
 Line = TextFile.ReadLine()
 If Line = Nothing Then
  Exit Do
 End If
 Me.ListBox1.Items.Add(Line)
 cnt = cnt + 1

‘文字列を位置(0,0)、青色で表示

 g.DrawString(Line, fnt, Brushes.Blue, 0, ystr)
 ystr = ystr + 20
Loop
TextFile.Close()

‘リソースを開放する

fnt.Dispose()
g.Dispose()
Label2.Text = cnt.ToString


End Sub

ボタン2

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

Dim ret As DialogResult
Dim textfile As IO.StreamWriter
Dim i As Integer
Dim cnt As Integer

 cnt = Integer.Parse(Label2.Text)

‘ダイアログボックスの初期設定

With Me.SaveFileDialog1
 .RestoreDirectory = True
  .OverwritePrompt = True
 .Filter = “すべてのファイル(.)|.|” & “テキストファイル(.txt)|.txt”
 .FileName = “ts.txt”
End With

‘ダイアログボックスの表示

ret = Me.SaveFileDialog1.ShowDialog
If ret = Windows.Forms.DialogResult.OK Then
 Me.Label1.Text =   Me.SaveFileDialog1.FileName

‘現在のファイルのエンコーディングで出力

‘textfile = New IO.StreamWriter(Me.Label1.Text, False, System.Text.Encoding.Default)

‘エンコーディングをShift-JISに指定する

textfile = New IO.StreamWriter(Me.Label1.Text, False, System.Text.Encoding.GetEncoding(\”Shift-JIS\”))

For i = 1 To ListBox1.Items.Count
 ‘Me.ListBox1.s = i – 1
 textfile.WriteLine(Me.ListBox1.Items(i – 1))
Next

textfile.Close()

End If

End Sub

End Class