vb.net - 如何在有多行时从文本文件中读取文本并生成一个字符串,以便我可以将其用作 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 阅读文本,但我无法拆分和加入这些文本。
解决方案
您可以创建一个将配置文件转换为 a 的方法,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
示例:现场演示
这个函数的作用是:
- 确保给出了路径
- 确保文件作为给定路径存在
- 循环遍历每一行
- 确保该行格式正确(键=值)
- 将键/值附加到字典
推荐阅读
- docker - 无法从 url 中删除 .html
- r - 找出每个可能范围的值在 R 中的三个独立变量中出现的总次数
- python - 使用 CamemBERT 找到问题的答案
- python - 双链表打印
- asp.net-core - 使用asp.net核心集标题样式将列表导出到excel
- jenkins - Kubernetes 上的詹金斯
- ruby-on-rails - 无法使用 Heroku 将图像上传到 Cloudinary
- python - 在调用多次返回字典的函数时,它返回空字典。为什么会发生这种情况,我该如何解决
- javascript - 如何从Javascript中的数组中删除“[”和“]”符号
- asp.net-mvc - 如果数据库中没有数据,那么如何在 asp.net 核心中显示“nodata”消息