vb.net 读取和保存txt文本文件

分享到: 更多

函数:ReadTxt 读取txt文件
参数为文件路径,返回值为文件内容

    Private Function ReadTxt(ByVal strFilePath As String) As String
        Dim mySr As System.IO.StreamReader
        Dim strS As String
        Dim n%
        strS = ""
        mySr = New System.IO.StreamReader(strFilePath, True)
        Do
            Dim line$ = mySr.ReadLine()
            strS = strS & line & vbCrLf
            n = n + 1
        Loop Until mySr.EndOfStream = True
        mySr.Close()
        Return strS
    End Function

过程:SaveTxt 保存为txt文件
第一个参数为保存的文件路径,第二个参数为要保存的内容
不过保存方式为追加,如果不想要之前的内容,可以先删除这个文件:

If Dir(strFilePath) <> "" Then File.Delete(strFilePath)
    Private Sub SaveTxt(ByVal strFilePath As String, ByVal strText As String)
        Dim mySw As System.IO.StreamWriter
        Dim strLine() As String
        mySw = New System.IO.StreamWriter(strFilePath, True)
        strLine = Split(strText, vbCrLf)
        For i As Integer = 0 To UBound(strLine)
            mySw.WriteLine(strLine(i))
        Next
        mySw.Close()
    End Sub

Leave a Reply

Google AdWords