Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

vb.net - How can I reasd text from text file while there are multiple line and generate a string so I can use it as sqlconnection string?

I have a config file which contain multiple lines.

DataBaseType =1
ServerName=LAPTOP-XXXX
Database=mydatabase
Connection Timeout=3000
User ID=sa
Password=sasa
ServerIp=xxxx:8083
ServiceType=http://
Backup Driver=D:
Backup Folder=SWBACKUP
Database Restore=D:

Now I want to generate a string which will be a sqlconnection string by reading,splitting and joining texts. it should be

"Data Source=LAPTOP-XXXX;Initial Catalog=mydatabase;User ID=sa;Password=sasa"

I am able to read text using streamreader , but I am not able to split and join those texts.

question from:https://stackoverflow.com/questions/65849495/how-can-i-reasd-text-from-text-file-while-there-are-multiple-line-and-generate-a

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can create a method that converts your config file to a Dictionary(Of String, String) and then get the values as needed.

Take a look at this example:

Private Function ReadConfigFile(path As String) As Dictionary(Of String, String)
    If (String.IsNullOrWhiteSpace(path)) Then
        Throw New ArgumentNullException("path")
    End If
    If (Not IO.File.Exists(path)) Then
        Throw New ArgumentException("The file does not exist.")
    End If

    Dim config = New Dictionary(Of String, String)
    Dim lines = IO.File.ReadAllLines(path)
    For Each line In lines
        Dim separator = line.IndexOf("=")
        If (separator < 0 OrElse separator = line.Length - 1) Then
            Throw New Exception("The following line is not in a valid format: " & line)
        End If

        Dim key = line.Substring(0, separator)
        Dim value = line.Substring(separator + 1)
        config.Add(key, value)
    Next

    Return config
End Function

Example: Live Demo

What this Function does is:

  1. Make sure that a path was given
  2. Make sure that the file exists as the given path
  3. Loop over each line
  4. Make sure that the line is in the correct format (key=value)
  5. Append the Key/Value to the Dictionary

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...