上一节重点学习了文本的编码,本节开始学习文本文件的读写。
通常的做法是建立一个与文件关联的filestream,然后使用StreamReader读取或者StreamWriter写入。
窗体设计界面如下:
同时请加入一个 OpenFileDialog控件和一个SaveFileDialog控件。
由于涉及文件操作和文本编码,
请在窗体顶部 Public Class Form1 上面中加入代码:
Imports System.IO Imports System.Text
窗体载入时,
Private Sub Form1_Load(sender As Object,e As EventArgs) Handles MyBase.Load With OpenFileDialog1 .Filter = "文本文件|*.txt" .FileName = "" .Multiselect = False End With SaveFileDialog1.Filter = "文本文件|*.txt" SaveFileDialog1.FileName = "" cbRead.SelectedIndex = 0 cbWrite.SelectedIndex = 0 End Sub
读取按钮按下时,根据cbRead的选项来选择读取的方法:
Private Sub btnRead_Click(sender As Object,e As EventArgs) Handles btnRead.Click Dim FilePath As String If OpenFileDialog1.ShowDialog <> DialogResult.OK Then Exit Sub End If FilePath = OpenFileDialog1.FileName lblFilePath.Text = "读取文件:" & FilePath txtFile.Text = "" Select Case cbRead.SelectedIndex Case 0 Call readText1(FilePath) Case 1 Call readText2(FilePath) Case 2 Call readText3(FilePath) Case 3 Call readText4(FilePath) Case 4 Call readText5(FilePath) Case 5 Call readText6(FilePath) End Select End Sub
写入按钮按下时,根据cbWrite的选项来选择写入的方法:
Private Sub btnWrite_Click(sender As Object,e As EventArgs) Handles btnWrite.Click Dim FilePath As String If SaveFileDialog1.ShowDialog <> DialogResult.OK Then Exit Sub End If FilePath = SaveFileDialog1.FileName Select Case cbWrite.SelectedIndex Case 0 Call writeText1(FilePath) Case 1 Call writeText2(FilePath) Case 2 Call writeText3(FilePath) Case 3 Call writeText4(FilePath) Case 4 Call writeText5(FilePath) Case 5 Call writeText6(FilePath) End Select lblFilePath.Text = "写入文件:" & FilePath End Sub
学习更多vb.net知识,请参看
vb.net 教程 目录
原文链接:https://www.f2er.com/vb/256536.html