【问题标题】:WriteAllText help in Visual Studio 2012Visual Studio 2012 中的 WriteAllText 帮助
【发布时间】:2015-01-31 18:58:36
【问题描述】:

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

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

有人知道我的代码有什么问题吗?抱歉,我对此很陌生。

【问题讨论】:

  • 你用Dim NewText As String = TextBox2.Text初始化变量NewText,顺便说一句,ReadAllLines 和WriteAllLines 会有所帮助
  • 是的,我已经初始化了 NewText(我的代码的第 3 行)。一切正常我只是想知道为什么它将我放入 TextBox2 的文本添加到文件的开头

标签: .net vb.net visual-studio-2012 file.readalllines


【解决方案1】:
Line 3: Dim NewText As String = TextBox2.Text

初始化 NewText = "HelloWorld"

然后你添加了第一行:

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

NewText 现在等于 "NewWorld" & lines(0) & NewLine

在第 3 行尝试Dim NewText = String.Empty

【讨论】:

  • 谢谢!!!我一直在努力解决这个问题,希望我能很快学会:P 再次感谢
猜你喜欢
  • 1970-01-01
  • 2021-10-04
  • 2010-09-17
  • 2012-08-17
  • 2011-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-19
相关资源
最近更新 更多