我如何从文本文件中读取文本,而有多行并生成字符串,以便我可以将其用作sqlconnection字符串?



我有一个包含多行的配置文件。

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:

现在我想生成一个字符串,这将是一个sqlconnection字符串通过读取,分割和连接文本。应该是

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

我能够使用streamreader阅读文本,但我不能分割和连接这些文本。

您可以创建一个方法,将您的配置文件转换为Dictionary(Of String, String),然后根据需要获取值。

看一下这个例子:

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

示例:Live Demo

这个函数的作用是:

  1. 确保给定了一个路径
  2. 确保文件作为给定路径存在
  3. 每行循环
  4. 确保行格式正确(key=value)
  5. 将键/值附加到字典

您可以使用readline方法,然后为数据库行制作如下内容:

Dim reader As New StreamReader(filetoimport.Txt, Encoding.Default)
Dim strLine As String
Do 
' Use ReadLine to read from your file line by line
strLine = reader.ReadLine 
Dim retString As String
'to get the string from position 0 length 8
retString = strLine .Substring(0, 8)
'check if match
if retString ="Database" Then
Dim valueString As String
valueString = strLine .Substring(9, strLine.length)
...

Loop Until strLine  Is Nothing

相关内容

最新更新