代码之家  ›  专栏  ›  技术社区  ›  Schpenn

从多行文本框写入.txt文件,然后读回

  •  2
  • Schpenn  · 技术社区  · 12 年前

    我有一个带有几个文本框的表单,我想将每个文本框的内容写入.txt文件中的新行。与中一样,用户填写一个表单,信息存储在文件中。然后我希望能够将文件中的信息检索到相同的文本框中。到目前为止,我可以做到这一点,但当其中一个文本框是多行的时,我会遇到问题。

    Printline(1, txtBox1.text)
    
    Printline(1, txtBox2.text)´which is the multiline one
    
    Printline(1, txtBox3.text)
    

    当我从文件中读回这篇文章时,我得到了多行文本框的第二行,我希望txtBox3中的文本位于该行。

    LineInput(1, txtBox1.text)
    
    LineInput(1, txtBox2.text)
    
    LineInput(1, txtBox3.text)
    

    如何将多行文本框中的所有行写入文件中的一行,然后将其作为多行文本盒中的单独行读回?

    我希望我说得有道理?我真的很想保留“一个txtBox-文件中的一行”的逻辑

    我想我需要使用不同的写作和阅读方法,但我对此并不熟悉,所以非常感谢任何帮助。

    3 回复  |  直到 11 年前
        1
  •  1
  •   varocarbas    12 年前

    你可以依靠 Lines 具有多行的情况下的属性。示例代码( curTextBox 是给定的吗 TextBox Control ):

    Using writer As System.IO.StreamWriter = New System.IO.StreamWriter("path", True)
        Dim curLine As String = curTextBox.Text
        If (curTextBox.Lines.Count > 1) Then
            curLine = ""
            For Each line As String In curTextBox.Lines
                curLine = curLine & " " & line
            Next
            curLine = curLine.Trim()
        End If
        writer.WriteLine(curLine)
    End Using
    

    注意:此代码将给定的 TextBox 独立于其行数。如果它有多行,它会包含一个空格来分隔各个行(所有行都可以放在文件的一行中)。您可能想通过添加不同的分隔字符来更改最后一个功能(替换 & " " & 和你想要的那个)。

        2
  •  0
  •   andyg0808 Lou Franco    12 年前

    一种选择是 escape 换行符,使它们不在输出中,然后在读回时取消它们的注释。

    下面是一些可以做到这一点的示例代码(我以前从未写过VB,所以这可能不是惯用的):

    ' To output to a file:
    Dim output As String = TextBox2.Text
    ' Escape all the backslashes and then the vbCrLfs
    output = output.Replace("\", "\bk").Replace(vbCrLf, "\crlf")
    ' Write the data from output to the file
    
    ' To read data from the file:
    Dim input As String = ' Put the data from the file in input
    ' Put vbCrLfs back for \crlf, then put \ for \bk
    input = input.Replace("\crlf", vbCrLf).Replace("\bk", "\")
    ' Put the text back in its box
    TextBox2.Text = input
    

    另一种选择是将您的数据存储在 XML , JSON YAML 。其中任何一种都是基于文本的格式,需要一个库来解析,但应该可以干净地处理您所拥有的多行文本,同时提供更大的未来灵活性。

        3
  •  0
  •   Ivan Aldaz    3 年前

    下一个简单的代码对我有效。

    将多行文字保存到文件中的单行:

    str = Replace(MyTextBox.Text, Chr(13) & Chr(10), "*LineFeed*") 'something recognizable
    Print #1, str 'no quotes
    

    要从文件中获取字符串并将其放在TextBox中,请执行以下操作:

    Line Input #1, str
    MyTextBox.Text = Replace(str, "*LineFeed*", Chr(13) & Chr(10))
    

    希望这能有所帮助

    推荐文章