Writing from multiline text box to .txt file, and then reading it back - vb.net

I have a form with several text boxes and I want to write the contents of each of them to a new line in a .txt file. As in, the user fills in a form, and the info is stored in the file. Then I want to be able to retrieve the info from the file into the same text boxes. I am able to do this, so far, but I encounter problems when one of the text boxes is multiline.
Printline(1, txtBox1.text)
Printline(1, txtBox2.text)´which is the multiline one
Printline(1, txtBox3.text)
When I read this back from the file I get the second line of the multiline text box where I want the text from txtBox3 to be.
LineInput(1, txtBox1.text)
LineInput(1, txtBox2.text)
LineInput(1, txtBox3.text)
How can I get all the lines from the multiline text box to write to one line in the file, and then read it back as separate lines in a multiline text box?
I hope I am making sense? I really would like to keep the logic of "one txtBox - one line in the file"
I guess I need to use different methods of writing and reading, but I am not that familiar with this, so any help is much appreciated.

You can rely on the Lines Property in case of having more than one line. Sample code (curTextBox is the given 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
NOTE: this code puts in one line all the text from the given TextBox independently upon its number of lines. If it has more than one line, it includes a blank space to separate the individual lines (all of them fitting in a single line of the file anyway). You might want to change this last feature by adding a different separating character (replace & " " & with the one you want).

One option would be to escape the newlines so that they aren't in the output, then unescape them on reading back in.
Here's some example code that will do this (I've never written VB before, so this probably isn't idiomatic):
' 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
Another option would be to store your data in XML, JSON, or YAML. Any of those are text-based formats that will require a library to parse, but should cleanly handle the multiline text you have, along with providing increased future flexibility.

the next simple code works for me.
Saving multiline text to a single line in a file:
str = Replace(MyTextBox.Text, Chr(13) & Chr(10), "*LineFeed*") 'something recognizable
Print #1, str 'no quotes
To get the string from the file and put it on a TextBox:
Line Input #1, str
MyTextBox.Text = Replace(str, "*LineFeed*", Chr(13) & Chr(10))
Hope this helps

Related

How to read a single line out of a word document

The method I used was for text files and gives gibberish as expected.
In: John Smith
Out: PK!~8ìz‡­[Content_Types].xml ¢( ´”ÏNÂ#Æï&¾C³WÓ.x0ÆP8•D|€a;…Õvw³;ü{{§´5#UôBRf¾ß÷Ív;½Áº,¢%ú ­IE7鈲™6³T¼Lâ[“Aa
¦bƒAú—½ÉÆaˆXmB*æDîNÊ æXBH¬CÕÜúˆýL:Po0CyÝéÜHe
¡¡˜*†è÷†˜Ã¢ h´æ¿ë$SmDt_÷UV©ç
­€¸,—&KÊÛ<×
I'm a novice at VBA, and I'm trying to read a document line by line so that I can eventually have the macro automatically remove entire lines based on their content.
Sub ayaya()
Dim TextLine As String
Open ActiveDocument.Path & "\Doc1.docm" For Input As #1
Do While Not EOF(1) ' Loop until end of file.
Line Input #1, TextLine ' Read line into variable.
Debug.Print TextLine
Loop
Close #1
End Sub
Part of me hoped that it would give "John Smith". I've seen some solutions put the entire document into a text file. Is there any way where I can delimit the data somehow? I'd like to be able to isolate a single line and remove it.
You are trying to read a docx or docm file, which is a zip archive. Word files are not plain text files, so you won't get anything meaningful treating them as such. You need to open the file with Word or another app that can read such files.

VBS Find/ replace double paragraph spacing with single spacing

I wasn't sure how to post a "question" that I found an answer to, but thought that it might be worth sharing my solution to save others the time I spent in figuring out how to do this.
Essentially, I have a PDF (with lots of pages/ formatting) that I want to strip the text out of, and paste into something else. However, a simple copy/paste will still leave text in its columns and automatically insert paragraph spaces that you then need to press end, delete, space, then repeat sequence indefinitely. Well, that's what programming was made for - doing repeated tasks for you so you don't have to.
My answer is posted below. If anyone has a better solution please let me know!
Below I pasted my code from a vbscript that I generated to do so. You will still need to go back through your text file and fix some bits & pieces after running the script that didn't follow the standard template that you programmed for.
Also, I'll note that I used notepad++ to determine how (in windows) Adobe reader handled carriage returns versus line feed (since the distinction is rather blurred today). I reference this article and the answer by AAT, which helped me in understanding the difference. The accepted answer is useful when specifically referencing vbs.
REM Set constants, then open file and copy into a buffer (contents)
Const ForReading = 1, ForWriting = 2
Dim fs, txt, contents
Set fs = CreateObject("Scripting.FileSystemObject")
Set txt = fs.OpenTextFile("originalTextFile.txt", ForReading)
contents = txt.ReadAll
txt.Close
REM Replace a double carriage return with un-repeatable text that as placeholder
contents = Replace(contents, vbCrLf & vbCrLf, "$%^&")
REM then replace leftover carriage returns with blank,
contents = Replace(contents, vbCrLf, "")
contents = Replace(contents, vbCrLf, "")
REM finally, restore original carriage returns for paragraph spacing
contents = Replace(contents, "$%^&", vbCrLf & vbCrLf)
contents = Replace(contents, "$%^&", vbCrLf & vbCrLf)
REM Write to file
Set txt = fs.OpenTextFile("textFileRemovedSpaces.txt", ForWriting)
txt.Write contents
txt.Close
MsgBox("Done!")
Step 1: Save pdf as a text file - this strips out the pictures/ etc. With Adobe Reader, do File -> Save as other -> Text.
Step 2: Save above as Something.vbs, and edit file names in script as appropriate. Make sure to also create the empty text file for the script to save the edited text in. Note in vbs, the text "REM" signifies a comment follows.
Step 3: Run Script.
Step 4: Profit!
I've find this useful, as it for the most part saves a lot of effort in editing a 300 page pdf that I needed to convert to a word document.
Again, if anyone has a better solution please let me know!

How do I search multiple textfiles for text, then adding that text into a listbox

I've got multiple text files within a folder, like this:
C:\Example\ 1.txt, 2.txt, 3.txt, 4.txt
The file names are generated by time and date they were created at so please don't try to open/search the documents using [1-4].txt or something similar as these are just examples.
I would like to search through all of these text files (without knowing their names as they're randomly generated), and if it matches certain text, I would like the rest of the text on that line to be added into a ListBox, then search the next/rest of the text files.
Example of text file contents:
[14:49:16] [Client thread/INFO]: Setting user: Users Name
All text after Setting user: which is on the same line should be added to the ListBox, so in this case, Users Name would be added.
The above text will always be the first line of the text file, so no need to search the whole file, the beginning of the text will always be the time created at (which will be different for each text file), then followed by [Client thread/INFO]: Setting user: which will always be the same for all of the text files, then Users Name , which wont actually output Users Name, this is what I would like to find, and then add to the ListBox.
I've got some of the code created, but there's three problems with it.
1: I have to define the name of the text file, which I will not know.
2: I'm not sure how to search through all of the documents, only the one that is defined.
3: I can get it to output the Users name, but only if I remove the leading time and [Client thread/INFO]:, but these items will always be there.
With these three problems, the code is useless, I'm just providing it as possibly it will make it easier for someone to help me?
Public Class Form1
Private Sub LoadFiles()
For Each line As String In IO.File.ReadLines("C:\Example\2016-09-28-1.txt")
'I had to define the name of the text file here, but I need to somehow automatically
'search all .txt files in that folder.
Dim params() As String = Split(line, ": ")
Select Case params(0)
'Text file has to be modified to show as:
Setting user: RandomNameHere
'for the RandomName to show within the ListBox,
'but normally it will never be shown like this within the text files.
Case "Setting user"
ListBox1.Items.Add(params(1))
End Select
Next
End Sub
Use System.IO.Directory.GetFiles to get the list of files, and System.IO.Path.GetExtension to filter for .txt files. The String.IndexOf function will let you search for text within each line of the file, and String.Substring will let you retrieve part of the line.
While your original code using Split could be made to work (you would need another loop to go through the split text), I think IndexOf and Substring are simpler in this case.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strFilenames() As String = System.IO.Directory.GetFiles("C:\Example")
For i As Integer = 0 To strFilenames.GetUpperBound(0)
Dim strFilename As String = strFilenames(i)
If System.IO.Path.GetExtension(strFilename).ToLower = ".txt" Then
For Each strLine As String In System.IO.File.ReadLines(strFilename)
'[14:49:16] [Client thread/INFO]: Setting user: Users Name
Dim strSearchText As String = "Setting user: "
Dim intPos As Integer = strLine.IndexOf(strSearchText)
If intPos > -1 Then
Dim strUsername As String = strLine.Substring(intPos + strSearchText.Length)
MsgBox(strFilename & " - " & strUsername) '<-- replace this with your SELECT CASE or whatever
End If
Next strLine
End If
Next i
End Sub
You can use system.io.directory class and use the getfiles method to get the filenames from a directoy. then you can open the file and do the needful.
https://msdn.microsoft.com/en-us/library/system.io.directory.getfiles(v=vs.110).aspx

VB.NET write just in the first line of file

I used over four different methods to get the text from a online text file: www.mysite.com/filedata.txt and overwrite it to another file.
Everything works, but I have only one problem. Everything is written in the first line and not the original format.
Example:
From:
Hello
Hi
Hi
To:
HelloHiHi
Here is just an example of a correct code which I'm using, but it doesn't work:
Using client As New WebClient()
client.DownloadFile("http://www.mystie.com/filedata.txt",
Application.StartupPath & "\file.txt")
End Using
The file is using a different line-break style that is not recognized by the edit control.
There are three different types of line-break styles that are in common usage: the Windows style (CR LF), the Unix style (LF), and the classic Mac style (CR).
Windows controls like the TextBox control naturally require the Windows style, CR LF. The corresponding escape characters for C# would be \r\n; on VB, you use ControlChars.CrLf or vbCrLf. On Unix, LF (\n, or ControlChars.Lf/vbLf) is more commonly encountered. If you are getting a file from an external source, like the Internet, it probably uses Unix-style line breaks, which aren't recognized as line breaks by the Windows TextBox control. The reason it works in what you call "advanced text editors" is that they support all these different styles of line-break characters.
This is exceedingly trivial to fix. Perform a character replacement on the string, replacing LF with CR+LF, before you display it in the TextBox.
' Download the file
Dim path As String = Application.StartupPath & "\file.txt"
Using client As New WebClient()
client.DownloadFile("http://www.mystie.com/filedata.txt", path))
End Using
' Read the file's text in as a string
Dim filedata As String = File.ReadAllText(path)
' Fix up the line endings
filedata = filedata.Replace(ControlChars.Lf, ControlChars.CrLf)
' Display the text in your TextBox
myTextBox.Text = filedata
I managed to solve everything by switching from textbox to richtextbox.

line input not working as expected in VBA

I have a text file that I open and attempt to read the individual lines. I have used the same code before on other files with no problem, but for some reason, this particular file is strange. When I do the following command;
Line Input #1, read_string
the string read_string contains the entire sequence of each line in the file concatenated together. When I look at the special chararcters of the file I do see a cariage return. But just so you know what the file looks like, here are the first two lines (daniweb formatting is too strange to print text here),
k_arr[8'h1C]= {10'b001111_0100,10'b110000_1011} ;
k_arr[8'h1C]= {10'b001111_0100,10'b110000_1011} ;
Anybody know how I can read each line? apparently line input doesnt work for this file.
Try
Dim lines() As String
lines = Split(read_string, vbCr) 'splitting with Carriage Return delimiter
'did it work?
Debug.Print lines(1)
Debug.Print lines(2) Dim lines() As String
Each element of the lines array should now contain one line of your text file.
If it didn't work, try with another delimiter instead of vbCr, e.g. vbLf (line feed).