加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 07:31:37 所属栏目:百科 来源:网络整理
导读:继续上一节,继续读写代码的编写。 为了简化操作,所有的Encoding均采用Encoding.Default。 读取方式5: 直接使用StreamReader('参数1:要打开的文件全路径,参数2:编码格式) 读取方式:循环读取指定数量的字符串, Private Sub readText5(ByVal filename
继续上一节,继续读写代码的编写。

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读