继续上一节,进入正式读写代码的编写。
为了简化操作,所有的Encoding均采用Encoding.Default。
读取方法1:
Private Sub readText1(ByVal filename As String) Dim textContent As String Dim fs As FileStream 'fs = New FileStream(filename,FileMode.OpenOrCreate,FileAccess.Read) fs = File.Open(filename,FileAccess.Read) Dim sr As New StreamReader(fs,Encoding.Default) textContent = sr.ReadToEnd() sr.Close() fs.Close() txtFile.Text = textContent End Sub
其中注释的一句
fs = New FileStream(filename,FileAccess.Read)
fs = New FileStream(filename,FileAccess.Read)
和后面一句
fs = File.Open(filename,FileAccess.Read)
等同,都是获得一个FileStream。
FileAccess.Read:采用read方式。由于这里是分别进行读和写,如果是读写都是用的同一个FileStream,请采用FileAccess.ReadWrite。
Private Sub writeText1(ByVal filename As String) Dim textContent As String = txtFile.Text Dim fs As FileStream 'fs = New FileStream(filename,FileAccess.Write) fs = File.Open(filename,FileAccess.Write) Dim sw As New StreamWriter(fs,Encoding.Default) sw.Write(textContent) sw.Close() fs.Close() End Sub
读取方法2:
直接使用StreamReader( 参数1:要打开的文件全路径,参数2:编码格式)
读取方式:一次性读取所有文本
读取方式:一次性读取所有文本
Private Sub readText2(ByVal filename As String) Dim textContent As String Dim sr As New StreamReader(filename,Encoding.Default) textContent = sr.ReadToEnd() sr.Close() txtFile.Text = textContent End Sub
写入方法2:
Private Sub writeText2(ByVal filename As String) Dim textContent As String = txtFile.Text Dim sw As New StreamWriter(filename,False) sw.Write(textContent) sw.Close() End Sub
由于.net平台下C#和vb.NET很相似,本文也可以为C#爱好者提供参考。
学习更多vb.net知识,请参看 vb.net 教程 目录