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 b As Integer, ch As String, mytext As String
        mytext = ""
        OFD1.FileName = ""
        OFD1.InitialDirectory = "E:\project\Exp11-1"  '设置初始目录为当前项目的根目录
        OFD1.Filter = "所有文本文件(*.txt)|*.txt"
        If OFD1.ShowDialog() <> DialogResult.OK Then
            Exit Sub
        End If
        fn = OFD1.FileName       '为打开文件对话框中选择的文件实例化文件流对象，并对其进行读操作
        fs = New FileStream(fn, FileMode.Open, FileAccess.Read)
        b = fs.ReadByte()       '从文件流中读取一个字节
        Do While b <> -1
            ch = Chr(b)         '将字节数据转换为字符
            mytext = mytext & ch
            b = fs.ReadByte()
        Loop
        TextBox1.Text = mytext     '将全部文件内容显示到TbContent文本框
        fs.Close()                  '关闭文件流对象
        BtnWrite.Enabled = True      '使"保存文件"按钮可用
    End Sub

    Private Sub BtnWrite_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnWrite.Click
        Dim len As Long, i As Integer
        Dim ch As String
        '建立FileStream对象，对已打开的文件进行保存。文件采用FileMode.Truncate模式，打开后将原有内容清空 
        fs = New FileStream(fn, FileMode.Truncate, FileAccess.Write)
        Dim bl As Boolean
        bl = fs.CanWrite
        len = TextBox1.Text.Length()
        For i = 1 To len            '将文本框中的字符逐个写入文件流
            ch = Mid(TextBox1.Text, i, 1)
            fs.WriteByte(Asc(ch))
        Next
        fs.Close()                  '关闭文件流对象
    End Sub
End Class
