vb.net 教程 4-8 文本文件读写 4

前端之家收集整理的这篇文章主要介绍了vb.net 教程 4-8 文本文件读写 4前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
继续上一节,继续读写代码的编写。

为了简化操作,所有的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,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 教程 目录

原文链接:https://www.f2er.com/vb/256530.html

猜你在找的VB相关文章