2015-01-31 56 views
0

所以我有一个程序正在处理,我需要读取.ini文件的行,然后将用户定义的文本写入该文件中的某一行。 到目前为止,我的一些代码:Visual Studio 2012中的WriteAllText帮助

Dim File As String = ".\TestFile.ini" 
    Dim FileText As String 
    Dim NewText As String = TextBox2.Text 
    Dim lines() As String 
    Dim separator() As String = {Environment.NewLine} 
    Dim x As Integer = 0 
    If My.Computer.FileSystem.FileExists(File) Then 
     FileText = My.Computer.FileSystem.ReadAllText(File) 
     lines = FileText.Split(separator, StringSplitOptions.RemoveEmptyEntries) 
     While x < lines.Length() 
      If lines(x).Contains("Nickname") Then 
       lines(x) = "Nickname" & "=" & TextBox2.Text 
      End If 
      NewText = NewText & lines(x) & Environment.NewLine 
      x = x + 1 
     End While 
     My.Computer.FileSystem.WriteAllText(File, NewText, False) 
    Else 
     MsgBox("File does not exist!") 
    End If 

文件我想编辑看起来像这样:

Don't edit this line 
Don't edit this line 
Don't edit this line 
Don't edit this line 
Nickname=test 
Don't edit this line 
Don't edit this line 
Don't edit this line 

我只是想4号线,但代码编辑这个单词“test”我已经这样做了,但也添加了我在TextBox2中放置的任何东西。像这样(假设我把HelloWorld放在TextBox2中):

HelloWorldDon't edit this line 
Don't edit this line 
Don't edit this line 
Don't edit this line 
Nickname=HelloWorld 
Don't edit this line 
Don't edit this line 
Don't edit this line 

任何人都知道我的代码有什么问题吗?对不起,我对此很新。

+0

初始化变量NewText'Dim NewText As String = TextBox2.Text',顺便说一句,ReadAllLines和WriteAllLines可以帮助 – Steve 2015-01-31 19:03:15

+0

是的,我已经初始化了NewText(我的代码的第三行)。一切正常,我只是想知道为什么它添加我把文本框2中的文本到文件的开头 – LukeSC1993 2015-01-31 19:44:46

回答

2
Line 3: Dim NewText As String = TextBox2.Text 

初始化NewText = “HelloWorld” 的

然后你添加的第一行:

Line 14: NewText = NewText & lines(0) & Environment.NewLine 

NewText现在等于 “新世界” &线(0)& NEWLINE

尝试Dim NewText = String.Empty为第3行。

+0

谢谢!我一直在努力弄清楚这一点,希望我很快会学到:P 再次感谢 – LukeSC1993 2015-01-31 22:44:34