Friday, April 4, 2014

Read & Write Txt File in vb.net

Add class form in vb.net project

Imports System
Imports System.IO
Imports System.Text
Imports System.Collections.Generic
Imports Scripting
Public Class Testwrite
    Public Sub DeleteFile(ByVal mydocpath As String, ByVal filename As String)
        Dim fso As FileSystemObject = New FileSystemObject
        If fso.FileExists(mydocpath + "\" & filename & ".set") = True Then
            fso.DeleteFile(mydocpath + "\" & filename & ".set", True)
        End If
    End Sub
    Public Sub WriteToFile(ByVal mydocpath As String, ByVal filename As String, ByVal datastring As String)
        Dim sb As New StringBuilder()
        sb.AppendLine(datastring)
        Using outfile As StreamWriter = New StreamWriter(mydocpath + "\" & filename & ".Txt", True)
            outfile.Write(sb.ToString())
        End Using
    End Sub
    Public Function ReadFromSetFile(ByVal mydocpath As String, ByVal filename As String, ByVal key As String) As String
        Dim txtbox As String = Nothing
        Try
            Using sr As StreamReader = New StreamReader(mydocpath + "\" & filename & ".set")
                While Not sr.EndOfStream
                    Dim line = sr.ReadLine()
                    Dim seppos As Integer = InStr(line, "|")
                    If seppos > 0 Then
                        If line Like key & "*" Then
                            txtbox = Trim(Mid(line, seppos + 1))
                            Exit While
                        End If
                    End If
                End While
            End Using
        Catch ex As Exception
            txtbox = ""
        End Try
        Return txtbox
    End Function
    Public Function ReadFromFile(ByVal mydocpath As String, ByVal title As Boolean) As String
        Dim line As String = Nothing
        Try
            Using sr As StreamReader = New StreamReader(mydocpath)
                If title = True Then
                    line = sr.ReadLine
                    line = Nothing
                End If
                While Not sr.EndOfStream
                    line = sr.ReadLine()
                End While
            End Using
        Catch
            line = ""
        End Try
        Return line
    End Function
End Class

No comments: