继续上一节,继续读写代码的编写。
为了简化操作,所有的Encoding均采用Encoding.Default。
读取方法3;
直接使用StreamReader(参数1:要打开的文件全路径,参数2:编码格式)
读取方式:循环读取一行文本
读取方式:循环读取一行文本
Private Sub readText3(ByVal filename As String) Dim textContent As String Dim sr As New StreamReader(filename,Encoding.Default) Do textContent = sr.ReadLine() If IsNothing(textContent) Then Exit Do txtFile.Text &= textContent & ControlChars.CrLf Loop While True sr.Close() End Sub
写入方法3:
Private Sub writeText3(ByVal filename As String) Dim textContent As String = txtFile.Text Dim sw As New StreamWriter(filename,False) Dim arrTextContent() As String = textContent.Split(ControlChars.CrLf) For i As Integer = 0 To arrTextContent.Length - 1 sw.WriteLine(arrTextContent(i)) Next sw.Close() End Sub使用时会发现,最后多写了一个回车。因为使用split的时候最后一个ControlChars.CrLf多带来了一个空字符串。请自行改正。
读取方法4:
Private Sub readText4(ByVal filename As String) Dim textContent As String Dim buffer() As Char Dim lenRead As Long Dim fs As New FileStream(filename,FileMode.OpenOrCreate,FileAccess.Read) lenRead = fs.Length Dim sr As New StreamReader(fs,Encoding.Default) ReDim buffer(lenRead - 1) sr.Read(buffer,lenRead) sr.Close() fs.Close() textContent = New String(buffer) txtFile.Text = textContent End Sub
写入方法4:
Private Sub writeText4(ByVal filename As String) Dim textContent As String = txtFile.Text Dim lenWrite As Long Dim fs As New FileStream(filename,FileAccess.ReadWrite) lenWrite = textContent.Length Dim sw As New StreamWriter(fs,Encoding.Default,lenWrite - 1) sw.WriteLine(textContent) sw.Close() fs.Close() End Sub
由于.net平台下C#和vb.NET很相似,本文也可以为C#爱好者提供参考。
学习更多vb.net知识,请参看 vb.net 教程 目录
原文链接:https://www.f2er.com/vb/256531.html