locked
Cannot save text in rich textbox if on multiple lines

    Question

  • Guys, here is the code i am using to read from a rich textbox:

     

    Dim mydir = my.computer.filesystem.currentdirectory
     IO.Path.GetFileName(mydir + "\record\" + tb_name.Text + ".txt" )
     Dim linebuffer() As String = IO.file.ReadAllLines(mydir + "\record\" + tb_name.Text + ".txt")
     casefiles.rb_casefile.Text = linebuffer(0).Trim(""""c)
    
    

     

    Code to write to file to save contents of rich textbox:

     

     

    FileOpen(1, mydir + tb_name.Text + ".txt", _
    				OpenMode.Output)
    			WriteLine(1, rb_casefile.Text)
    			FileClose(1)
    			MsgBox("Save successful.", _
    			MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, "Information")
    

     

    Unfortunately it will only read the first line of the rich textbox. What do you suggest is the best way of overcoming this problem without calling linebuffer multiple times?

     




    Friday, April 15, 2011 7:27 PM

Answers

  • I guess i deserve a dunce cap on that one LOL

     Sorry I just wasn't thinking about the routine I guess. Here is the append that should work I did test this and it did work for me.

     Sub append()
        Dim mydir = My.Computer.FileSystem.CurrentDirectory
        Using sw As New IO.StreamWriter(mydir + "\" + "test" + ".txt", True)
          sw.WriteLine()
          sw.Write(tb_name.Lines)
    
        End Using
    
      End Sub
    


    Hope this helps Curtis, Always Lost in Code, Always mark answers as correct if they answer you question and solve your problem. This way others when searching for similar problems can find the answer faster.
    • Marked as answer by SolidiusWolf Wednesday, April 20, 2011 12:02 PM
    Tuesday, April 19, 2011 10:29 PM

All replies

  • Why are you using those methods to write the file? They are very old and all but obsolete. The richtextbox control has its own .SaveFile method you can call directly. It accepts a string of the full file path where you want to save the file. Much easier and 1 line of code to save the text in the richtextbox to file.
    Matt Kleinwaks - MSMVP MSDN Forums Moderator - www.zerosandtheone.com
    Friday, April 15, 2011 7:45 PM
    Moderator
  • Hi SolidiusWolf,

    It's normal because you're only locating element 1 of linebuffer array by linebuffer(0). However you have redundant lines as well as legacy methods like FileOpen (FileStream or IO.File.WriteAllxxx methods are better), however i'll try to describe the solution of your main problem about getting the entire file content.Simply assign array to Lines property of RTB (rb_casefile) like this:

    Dim mydir = my.computer.filesystem.currentdirectory

     Dim linebuffer() As String = IO.file.ReadAllLines(mydir + "\record\" + tb_name.Text + ".txt")
     casefiles.rb_casefile.Lines = linebuffer

    ...but it seems you also want to apply "trimming"  quotation mark(s) against each line of your array by meaning """" (four quotes), so designate value assignment like this (using "replace" is better to remove all occurences of quotation marks):

    Dim mydir = my.computer.filesystem.currentdirectory

     Dim linebuffer() As String = IO.file.ReadAllLines(mydir + "\record\" + tb_name.Text + ".txt")
     casefiles.rb_casefile.Lines = linebuffer
    casefiles.rb_casefile.Text = casefiles.rb_casefile.Text.Replace("""", String.Empty)

    ...or if you still want to use "trim" function just to remove "leading" and "trailing" quotation marks, use this:

    Dim mydir = my.computer.filesystem.currentdirectory

     Dim linebuffer() As String = IO.file.ReadAllLines(mydir + "\record\" + tb_name.Text + ".txt")

    For x As Integer = 0 To linebuffer.Length - 1

                linebuffer(x) = linebuffer(x).Trim(""""c)
     Next

    casefiles.rb_casefile.Lines = linebuffer

    Note that your second line: IO.Path.GetFileName is redundant has no effect on code.

    HTH.


    Best regards, Saygılarımla, Onur Güzel

    Yazgeliştir Forumları VB.NET / C# Moderatorü.

    Microsoft Haber Grupları Profilim (VB.NET)




    Friday, April 15, 2011 8:15 PM
  • Onur thank you but may i quickly say something. I am doubtful your solution will work and that is my fault for being misleading. The text file that we will be reading from will contain other values in them (two more lines of text in the file that other controls will use). So to be more specific, what i really need is a way of reading lines of text that exclude the other ones that the other controls will read from.

     

    I could reorder the code so that the richtextbox is the last to write to the file but that still needs code to exclude the other lines of text in the text file.


    Friday, April 15, 2011 8:32 PM
  • Onur thank you but may i quickly say something. I am doubtful your solution will work and that is my fault for being misleading. The text file that we will be reading from will contain other values in them (two more lines of text in the file that other controls will use). So to be more specific, what i really need is a way of reading lines of text that exclude the other ones that the other controls will read from.

     

    I could reorder the code so that the richtextbox is the last to write to the file but that still needs code to exclude the other lines of text in the text file.



    Hi SolidiusWolf,

    Please see my previous, edited post and see if it helps. What kind of thing are you trying to achieve? Can you post some example containing the input of text file and with the desired output on richtextbox? What kind of values are you meaning to exclude? Hope this helps.


    Best regards, Saygılarımla, Onur Güzel

    Yazgeliştir Forumları VB.NET / C# Moderatorü.

    Microsoft Haber Grupları Profilim (VB.NET)




    Friday, April 15, 2011 8:38 PM
  • Onur imagine you have a database software with 10 text fields. One of those fields are a richtextbox where you store the address. Now if i press SPACE on the rich textbox and start a new line, it saves like this on the text file we write to when we save:

    "line number 1"  - richtextbox first sentence

    "line number 2" - richtextbox first sentence

    "name text"

    "surname text"

    So when we read the values of the richtextbox from the file it only shows "line number 1". can i merge these lines together without affecting the other text in the file?

    Friday, April 15, 2011 8:59 PM
  • Onur imagine you have a database software with 10 text fields. One of those fields are a richtextbox where you store the address. Now if i press SPACE on the rich textbox and start a new line, it saves like this on the text file we write to when we save:

    "line number 1"  - richtextbox first sentence

    "line number 2" - richtextbox first sentence

    "name text"

    "surname text"

    So when we read the values of the richtextbox from the file it only shows "line number 1". can i merge these lines together without affecting the other text in the file?


    If i understood correctly, you want to preserve existing structure of text file and you want to "append" the content of file, thus reading it back would provide preserved content. If this is the case (sorry if i'm missing something, that's all i've made out by your statements):

    You have 2 main options:

    1) Read all the existing content from file then add which line you want in RTB, then save the updated/the whole RTB content (richtextbox) using WriteAllLines:

    ' To read existing content first call read sub, preferably on form_load (when RTB is constructed).

      Sub read()
            Dim mydir = My.Computer.FileSystem.CurrentDirectory
            Dim linebuffer() As String = IO.File.ReadAllLines(mydir + "\record\" + tb_name.Text + ".txt")
            casefiles.rb_casefile.Lines = linebuffer
        End Sub

    ' Then add some lines, and append/overwrite content manually on RTB, then write new lines

     Sub write()
            Dim mydir = My.Computer.FileSystem.CurrentDirectory
            IO.File.WriteAllLines(mydir + "\record\" + tb_name.Text + ".txt", rb_casefile.Lines)
        End Sub

    ..call write() sub when you're done with editing RTB lines.

    2) Use StreamWriter to add and save new lines using the code:

            Dim mydir = My.Computer.FileSystem.CurrentDirectory
            Using sw As New IO.StreamWriter(mydir + "\record\" + tb_name.Text + ".txt", True)
                sw.WriteLine()
                sw.Write("write something new here")
            End Using

    ..note that WriteLine() creates a line terminator (vbNewline or CrLf, it's optional). And second parameter in StreamWriter's constructor (Append) is True to preserve existing file content.

    http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx

    Hope this helps.


    Best regards, Saygılarımla, Onur Güzel

    Yazgeliştir Forumları VB.NET / C# Moderatorü.

    Microsoft Haber Grupları Profilim (VB.NET)



    Friday, April 15, 2011 9:45 PM
  • That is far too complicated. There must be an easier way. Why is it so hard to read a particular line?

    Even when you use the write method to write to a textfile, it shows up as "line1line2" together. So why cant you just read the first line and have the program show it as:

    line 1

    line 2

    without harming the other lines in the text file???

    Saturday, April 16, 2011 3:51 PM
  • Hi solidiuswolf,

     It is so hard because files have to have some type of delimter to seperate the various sections of the file. This is to allow a way to get each section of the file. Without this delimiter there is no way for the code to know where one portion of the text that is needed starts and ends.

    For example the two texts "The brown wolf has a limp" and " This limp is caused by a thorn in his paw" now if this is saved directly from the variables to a file you would have "The brown wolf has a limpThis limp is caused by a thorn in his paw" Now as can be seen how would the code know where one text begins or ends. So we use delimiters for this such as a ":" between texts so the same text with a delimiter would be saved as "The brown wolf has a limp:This limp is caused by a thorn in his paw" Now we can look for the delimiter that seperates the text in the file, use that and the number of texts in the file to know what is to be used where.

    The CrLf is used in rich textboxes to determine the end of a line. But this is not in a regular textbox that has only one line so some type of delimter must be used. So when we have two or more text boxes and these are mixed in with richtextboxes you need to add a delimiter to the string so they can be seperated when the file is loaded back in.

     

     


    Curtis Always Lost in Code, Always mark answers as correct if they answer you question and solve your problem. This way others when searching for similar problems can find the answer faster.
    Saturday, April 16, 2011 4:34 PM
  • SolidiusWolf,

     Here is an example of an array being saved to a text file this same principle applies to saving textboxes. I know this is older code but it deminstrates the delimter use better. This was written for a game save. but as you can see it takes an array of strings and saves them as a file using a seperater between each array string that is added to the text file.

     Private Sub btnOpenGame_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpenGame.Click
        Dim filename As String = "your file name"
        If IO.Directory.Exists(My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\Your Directoy" & filename) Then
          Dim openfile As String
          Dim i As Integer
          Dim theStreamReader As New StreamReader((My.Computer.FileSystem.SpecialDirectories.MyDocuments _
                                  & "Your Directory") + filename)
          openfile = theStreamReader.ReadToEnd()
          theStreamReader.Close()
          ' The colon is a delimter used to seperate values
          Dim labelsplit() As String = Split(openfile, ":")
          For i = 0 To labelsplit.Count - 1
            CurButtons(i) = labelsplit(i)
          Next
        End If
    
    
    
      End Sub
    
      Private Sub btnSaveGame_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveGame.Click
        Dim filename As String = "your file name"
        Dim i As Integer
        Dim gamesave As String
        If Not IO.Directory.Exists(My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\Your Directoy=" & filename) Then
          'Create Destination directory firt
          IO.Directory.CreateDirectory(My.Computer.FileSystem.SpecialDirectories.MyDocuments _
                         & "\Your Directoy" & filename)
    
        End If
        Dim theStreamWriter As New StreamWriter(My.Computer.FileSystem.SpecialDirectories.MyDocuments _
                                       & "\Your Directoy" & filename)
        ' The colon is a delimter used to seperate values and must be saved between values
        For Each number As String In CurButtons(i)
          gamesave += CurButtons(i) & ":"
        Next
        theStreamWriter.Write(gamesave)
        theStreamWriter.Close()
        
      End Sub
    


    Curtis,<crlf> Always Lost in Code, Always mark answers as correct if they answer you question and solve your problem. This way others when searching for similar problems can find the answer faster.
    Saturday, April 16, 2011 4:46 PM
  • I tried carrying that code over but i got 11 errors. With all due respect but i am an utter noob :(

    i could never do or understand something like this. why is it so complicated?




    Saturday, April 16, 2011 5:04 PM
  • SolidiusWolf,

     I used Onur suggestion and made up the code for you. This will get the Rich textbox and save it to a file. Then it will load this text back into a richtextbox.

    Now if you are adding text to the file after the file has been created then you will have to call append sub. Replace "Test" with your filename.

      Private Sub btnOpenGame_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpenGame.Click
        Dim mydir = My.Computer.FileSystem.CurrentDirectory
        Dim linebuffer() As String = IO.File.ReadAllLines(mydir + "\" + "test" + ".txt")
        tb_name.Lines = linebuffer
    
      End Sub
    
      Private Sub btnSaveGame_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveGame.Click
    
        Dim mydir = My.Computer.FileSystem.CurrentDirectory
        IO.File.WriteAllLines(mydir + "\" + "test" + ".txt", tb_name.Lines)
      End Sub
    
    
      Sub append()
        Dim mydir = My.Computer.FileSystem.CurrentDirectory
        Using sw As New IO.StreamWriter(mydir + "\" + "test" + ".txt", tb_name.Lines)
          sw.WriteLine()
          sw.Write("write something new here")
        End Using
    
      End Sub
    

    Hope this helps Curtis, Always Lost in Code, Always mark answers as correct if they answer you question and solve your problem. This way others when searching for similar problems can find the answer faster.
    • Proposed as answer by Zeldacat Saturday, April 16, 2011 9:18 PM
    • Unproposed as answer by SolidiusWolf Tuesday, April 19, 2011 10:51 AM
    Saturday, April 16, 2011 7:08 PM
  • Curtis, for the append sub : Overload resolution failed because no accessible "New" can be called with these arguments.

     

    Using sw As New IO.StreamWriter

    Tuesday, April 19, 2011 10:57 AM
  • I guess i deserve a dunce cap on that one LOL

     Sorry I just wasn't thinking about the routine I guess. Here is the append that should work I did test this and it did work for me.

     Sub append()
        Dim mydir = My.Computer.FileSystem.CurrentDirectory
        Using sw As New IO.StreamWriter(mydir + "\" + "test" + ".txt", True)
          sw.WriteLine()
          sw.Write(tb_name.Lines)
    
        End Using
    
      End Sub
    


    Hope this helps Curtis, Always Lost in Code, Always mark answers as correct if they answer you question and solve your problem. This way others when searching for similar problems can find the answer faster.
    • Marked as answer by SolidiusWolf Wednesday, April 20, 2011 12:02 PM
    Tuesday, April 19, 2011 10:29 PM
  • Thanks Curtis.
    Wednesday, April 20, 2011 12:02 PM