2016-03-21 145 views
1

我是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

我已经使用多行来提高可读性。我希望你没关系。 –

+0

这个“UserName = Unnamed”的情况是多个实例还是只有一个? –

+0

如果您使用INI解析器,请参阅我的** IniManager **类(以及里面的注释示例):https://github.com/ElektroStudios/ElektroKit/tree/master/Solution/v1.2/Elektro.Application 。设置/类型 – ElektroStudios

回答

2
Dim newText = text.Replace("UserName = Unnamed", "UserName = " & TextBox_NewUser.Text) 
+0

或者: 'Dim newText = text.Replace(“Unnamed”,TextBox_NewUser.Text)' – OSKM

+0

感谢您的回复,但您会发现“未命名”是可变的,可能是任何内容。所以,如果我试图再次将我的名字改为别的东西,那么它就不起作用。 – Darius47

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

+0

请试试这个凯伦,谢谢。对于这样一个简单的任务,代码看起来有点复杂。 – Darius47

+0

嗨Darius47,关于一个简单任务的复杂代码,它完全依赖于一个人的知识水平,在这种情况下是vb.net语言。当然你可以随着第一个答案走,这可能更符合你的喜好,因为它非常简单。这是这个网站的美丽,你可以通过不同的方式来解决一个问题:-) –