Imports System.IO           '引入命名空间
Public Class Form1
    Dim fs As FileStream    '定义文件流对象
    Dim fn As String        '定义字符串用于存放要操作的文件路径及文件名
    Private Sub BtnRead_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnRead.Click
        Dim line As String
        Dim sr As StreamReader
        OFD1.FileName = ""
        OFD1.InitialDirectory = "E:\project\Exp11-2"  '设置初始目录为当前项目的根目录
        OFD1.Filter = "所有文本文件(*.txt)|*.txt"
        If OFD1.ShowDialog() <> DialogResult.OK Then
            Exit Sub
        End If
        TextBox1.Text = ""
        fn = OFD1.FileName       '为打开文件对话框中选择的文件实例化StreamReader对象
        sr = New StreamReader(fn)
        Do While sr.Peek <> -1      '如果不是文件尾
            line = sr.ReadLine()   '从流中读取一行
            '将读取的行显示到文本框
            TextBox1.Text = TextBox1.Text & line & vbCrLf
        Loop
        sr.Close()                  '关闭流
        BtnWrite.Enabled = True      '使"保存文件"按钮可用
    End Sub

    Private Sub BtnWrite_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnWrite.Click
        Dim i As Integer
        Dim sw As StreamWriter
        '建立StreamWrite对象，对已打开的文件进行保存
        sw = New StreamWriter(fn)
        For i = 0 To TextBox1.Lines.Length() - 1   '遍历文本框中的所有行
            sw.WriteLine(TextBox1.Lines(i))        '把第i行写入文件
        Next
        sw.Close()                  '关闭流
    End Sub
End Class
