我是vb.net的新手,我正在尝试做一些非常简单的事情。我有这个代码从.ini文件读取特定的文本行。
Dim FilePath As String = Application.StartupPath & "\bin\userconfig.ini"
Dim text As String = IO.File.ReadAllText(FilePath)
Dim newText = text.Replace("UserName = ", TextBox_NewUser.Text)
IO.File.WriteAllText(FilePath, newText)
如何在"="
之后用TextBox_NewUser
中输入的内容替换该行文本。正如您在当前代码中看到的那样,它只是替换了我不想要的整个"UserName ="
。
默认情况下,.ini中的特定文本行具有以下值:
"UserName = Unnamed"
那么如何使用"Unnamed"
中输入的内容替换TextBox_NewUser
?
非常感谢任何帮助。
答案 0 :(得分:2)
sqlite data
答案 1 :(得分:0)
这是另一种解决方法,还有其他可以做到的断言,例如:下面的代码假设这些行不是以空格开头,如果是这样的话,你会先使用StartsWith等对每一行进行修剪。
配置文件
Role = Moderator
UserName = xxxx
Joined = 09/23/1006
代码
Public Class Form1
Private fileName As String =
IO.Path.Combine(
AppDomain.CurrentDomain.BaseDirectory, "userConfig.ini")
''' <summary>
''' assumes the file exist but does not assume there is text in
''' the text box.
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If Not String.IsNullOrWhiteSpace(TextBox_NewUser.Text) Then
Dim lines As List(Of String) = IO.File.ReadAllLines(fileName).ToList
For index As Integer = 0 To lines.Count - 1
If lines(index).ToLower.StartsWith("username") Then
lines(index) = String.Concat("UserName = ", TextBox_NewUser.Text)
End If
Next
IO.File.WriteAllLines(fileName, lines.ToArray)
End If
End Sub
End Class
Microsoft OneDrive,VS2013上的示例项目 https://onedrive.live.com/redir?resid=A3D5A9A9A28080D1!907&authkey=!AKQCanSTiCLP4mE&ithint=file%2czip