版权声明:本文为博主原创文章,转载请在显著位置标明本文出处以及作者网名,未经作者允许不得用于商业目的。
继续上一节,继续读写代码的编写。
为了简化操作,所有的Encoding均采用Encoding.Default。
读取方式5:
直接使用StreamReader( '参数1:要打开的文件全路径,参数2:编码格式)
读取方式:循环读取指定数量的字符串,
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, 0, lenRead)
If readLength <= 0 Then Exit Do
textContent = New String(buffer)
txtFile.Text &= textContent
Loop While True
sr.Close()
End Sub
写入方法5:
直接使用StreamWriter( 参数1:要写入的文件全路径,参数2:编码格式)
写入方式:循环写入指定数量的字符串
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
以上提供了6种读写文本文件的方法,各位读者请根据实际情况使用最方便的方法。
由于.net平台下C#和vb.NET很相似,本文也可以为C#爱好者提供参考。
学习更多vb.net知识,请参看vb.net教程 目录
————————————————
版权声明:本文为CSDN博主「VB.Net」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。