我尝试使用.txt文件创建一个配置文件,在这里我发现很难阅读格式的内容..已经从昨天我在谷歌搜索,但没有像我这样的类似情况或者我错过了它..
我的.txt内容如下:
Cek Server IP = 192.168.10.1
服务器IP = 192.168.10.1
Cek My Website = www.google.com
我的网站= www.anothersite.com
这是我的代码:
WebControl.Source = New Uri("about:blank")
If My.Computer.Network.Ping("XXX") Then
WebControl.Source = New Uri("ZZZ")
Else
MsgBox("CANNOT CONNECT TO SERVER")
Exit Sub
End If
我想要的是如何获取值“192.168.10.1”从“Cek服务器IP”然后发送到“XXX”并从“服务器IP”获取值“192.168.10.1”然后发送到“ZZZ”
我该怎么做?
Sory因为我的英语不好。感谢。
答案 0 :(得分:0)
根据我的理解,您希望通过提供密钥来读取.txt文件中的值。为此,您必须首先编写一个函数,将一个键作为参数获取并返回值:
private String GetValue(String key)
{
Boolean isValueFound = false;
String line = null;
//Open your file
using (StreamReader sr = new StreamReader("YourFile.txt"))
{
//Read it line-by-line
while ((line = sr.ReadLine()) != null)
{
//When the required line is found, set the flag and come out of the loop
if (line.Trim().StartsWith(key))
{
isValueFound = true;
break;
}
}
}
if (isValueFound)
{
//Split the line by using = as separator. So at index 0, you have the key and at index 1 you have the value
String[] strArray = line.Split('=');
//Trim the value before returning to get rid of extra spaces
return strArray[1].Trim();
}
else
{
//if value is not found, return null
return null;
}
}
现在你可以这样调用上面的函数:
//This line will give you 192.168.10.1
String result = this.GetValue("Cek Server IP");
//This line will return www.google.com
result = this.GetValue("Cek My Website");
答案 1 :(得分:0)
对于文件I / O,System.IO.File
类有一些有用的方法,对于文本文件,ReadLines
方法可能就是你想要的。然后,您可以使用String.Contains
来检查=
字符,并使用String.Split
将这些行分隔为键和值部分。
您可以将其包装到一个类中以读取和解析您的配置文件,并允许您访问特定值,例如: (您可能需要一些Import
和Option Infer On
):
Public Class SettingsFile
Private ReadOnly _settings As IDictionary(Of String, String)
Private Sub New(settings As IDictionary(Of String, String))
_settings = settings
End Sub
Public Default ReadOnly Property Item(name As String) As String
Get
Dim value As String = Nothing
_settings.TryGetValue(name, value)
Return value
End Get
End Property
Public Shared Function Load(fileName As String) As SettingsFile
Dim settings = New Dictionary(Of String, String)()
For Each line In File.ReadLines(fileName).Where(Function(x) x.Contains("="))
Dim parts = line.Split("="c)
If parts.Count = 2 Then
settings(parts(0).Trim()) = parts(1).Trim()
End If
Next
Return New SettingsFile(settings)
End Function
End Class
然后,您可以在代码中使用此类,例如:
Dim s = SettingsFile.Load("C:\Path\To\Settings.txt")
Dim s1 = s("Cek Server IP") ' 192.168.10.1
Dim s2 = s("Cek My Website") ' www.google.com
Dim s3 = s("Bad Key") ' Nothing