继续上一节,继续读写代码的编写。
为了简化操作,所有的Encoding均采用Encoding.Default。
读取方式5:
Private Sub readText5(ByVal filename As String) Dim textContent As String Dim buffer() As Char Dim lenRead As Integer = 200 Dim readLength As Integer Dim sr As New StreamReader(filename,Encoding.Default) Do ReDim buffer(lenRead - 1) readLength = sr.Read(buffer,lenRead) If readLength <= 0 Then Exit Do textContent = New String(buffer) txtFile.Text &= textContent Loop While True sr.Close() End Sub
写入方法5:
Private Sub writeText5(ByVal filename As String) Dim textContent As String = txtFile.Text Dim buffer() As Char = textContent.tocharArray Dim lenTotal As Long = buffer.Length Dim lenWrite As Integer = 30 Dim buffPos As Integer = 0 'Dim fs As New FileStream(filename,FileMode.OpenOrCreate) 'Dim sw As New StreamWriter(fs) Dim sw As New StreamWriter(filename, False) Do While buffPos < lenTotal If buffPos + lenWrite > lenTotal Then lenWrite = lenTotal - buffPos End If sw.Write(buffer,buffPos,lenWrite) buffPos += lenWrite Loop sw.Close() End Sub
读取方式6:
直接使用File的方法ReadAllText()
Private Sub readText6(ByVal filename As String) Dim textContent As String textContent = File.ReadAllText(filename,Encoding.Default) txtFile.Text = textContent End Sub
写入方式6:
直接使用File的方法WriteAllText()
Private Sub writeText6(ByVal filename As String) Dim textContent As String = txtFile.Text File.WriteAllText(filename,textContent,Encoding.Default) End Sub
由于.net平台下C#和vb.NET很相似,本文也可以为C#爱好者提供参考。
学习更多vb.net知识,请参看 vb.net 教程 目录