Differences Between vbLf, vbCrLf & vbCr Constants - vb.net

I used constants like vbLf , vbCrLf & vbCr in a MsgBox; it produces same output in a MsgBox (Text "Hai" appears in a first paragraph and a word "Welcome" appears in a next Paragraph )
MsgBox("Hai" & vbLf & "Welcome")
MsgBox ("Hai" & vbCrLf & "Welcome")
MsgBox("Hai" & vbCr & "Welcome")
I know vbLf , vbCrLf & vbCr are used for print and display functions.
I want to know the Difference between the vbLf , vbCrLf & vbCr constants.

Constant Value Description
----------------------------------------------------------------
vbCr Chr(13) Carriage return
vbCrLf Chr(13) & Chr(10) Carriage return–linefeed combination
vbLf Chr(10) Line feed
vbCr : - return to line beginning
Represents a carriage-return character for print and display functions.
vbCrLf : - similar to pressing Enter
Represents a carriage-return character combined with a linefeed character for print and display
functions.
vbLf : - go to next line
Represents a linefeed character for print and display functions.
Read More from Constants Class

The three constants have similar functions nowadays, but different historical origins, and very occasionally you may be required to use one or the other.
You need to think back to the days of old manual typewriters to get the origins of this. There are two distinct actions needed to start a new line of text:
move the typing head back to the left. In practice in a typewriter this is done by moving the roll which carries the paper (the "carriage") all the way back to the right -- the typing head is fixed. This is a carriage return.
move the paper up by the width of one line. This is a line feed.
In computers, these two actions are represented by two different characters - carriage return is CR, ASCII character 13, vbCr; line feed is LF, ASCII character 10, vbLf. In the old days of teletypes and line printers, the printer needed to be sent these two characters -- traditionally in the sequence CRLF -- to start a new line, and so the CRLF combination -- vbCrLf -- became a traditional line ending sequence, in some computing environments.
The problem was, of course, that it made just as much sense to only use one character to mark the line ending, and have the terminal or printer perform both the carriage return and line feed actions automatically. And so before you knew it, we had 3 different valid line endings: LF alone (used in Unix and Macintoshes), CR alone (apparently used in older Mac OSes) and the CRLF combination (used in DOS, and hence in Windows). This in turn led to the complications of DOS / Windows programs having the option of opening files in text mode, where any CRLF pair read from the file was converted to a single CR (and vice versa when writing).
So - to cut a (much too) long story short - there are historical reasons for the existence of the three separate line separators, which are now often irrelevant: and perhaps the best course of action in .NET is to use Environment.NewLine which means someone else has decided for you which to use, and future portability issues should be reduced.

Related

Indentify line breaks in excel VBA

I'm trying to identify a cell has line breaks(not the menu bar cell option, actual multiple lines through alt+enter), and extract each line separatedely
I have tried both
InStr(str, "\n") < 0
and
Split(str, "\n")
But doesn't seem to be working
VBA is not C# ("\n"). Line breaks you'll find on: vbCr or vbLf or vbCrLf constants.
For further information, please see:
vbCr
vbLf
vbCrLf
[EDIT]
Points to Mat's Mug answer! I forgot about vbNewLine constant.
There are no escape sequences in VBA. Use the built-in vbNewLine constant instead for the equivalent:
hasLineBreaks = InStr(str, vbNewLine) > 0
Per MSDN, vbNewline returns a Platform-specific new line character; whichever is appropriate for current platform, that is:
Chr(13) + Chr(10) [on Windows] or, on the Macintosh, Chr(13)
So you don't need to work with ASCII character codes, or even with their respective built-in constants.
Except Excel will strip CR chars from cell and shape contents, and this has nothing to do with VBA (the CR chars would be stripped all the same and "\n" wouldn't work for correctly reading that Excel data in C#, Javascript, or Python either) and everything to do with the context of where the string came from.
To read "line breaks" in a string with the CR chars stripped, you need to look for line feed chars in the string (vbLf).
But if you systematically treat the line feed character as a line ending, you'll eventually run into problems (esp.cross-platform), because ASCII 10 all by itself isn't an actual line break on either platform, and you'll find ASCII 13 characters in strings you thought you had stripped line breaks from, and they'll still properly line-break on a Mac, but not on Windows.
Consider either:
Split(str, Chr(10))
or
Split(str, Chr(13))
You may need to try both if the data has been imported from external source.

Word Interop Text replace in header adding extra spaces

Morning Everyone,
using interop.word to do a find/replace in the header. It works but word, in it's great wisdom, adds spaces: 1 space to the beginning of each line after the first, 2-3 spaces at the end of each line.
So it looks like this but it should be completely left:
Sept 2, 2015
first name
last name
address
I am looking at the text of the header after replacement using headerfooter.range.text and there are no extra spaces so it has to be an auto-formatting issue that word is obsessed with.
Thanks for any help!
What I have tried with no luck:
paragraphformat.duplicate before and reset after
range.paragraphformat.spacebefore = 0
range.paragraphformat.spaceafter = 0
Dim info As String = Now.ToLongDateString & vbCrLf & Trim(PersonInformation.FullName) & vbCrLf & Trim(PersonInformation.Address)
info &= vbCrLf & Trim(PersonInformation.City & ", " & PersonInformation.State & " " & PersonInformation.Zip)
hf.Range.Find.Execute(TagToReplace, , , , , , , , , info)
UPDATED
Found the answer. It is how word/interop interprets vbcrlf when generating the doc. Using just vbcr did the trick. vblf also caused the inserted space. Incidentally, vbNewLine also caused the extra space to appear.
Found the answer. It is how word/interop interprets vbcrlf when generating the doc. Using just vbcr did the trick. vblf also caused the inserted space. Incidentally, vbNewLine also caused the extra space to appear.

Escape Characters in a resource file string?

I've been globalizing an application and have been using Resx Manager to make my life easier. I ran into a multi-line string literal and it stumped me.
How would I handle the escape characters when making this string into a resource?
If Not RelayMessage(
"Are you sure you want to do the selected action?" & vbCrLf &
"A confirmation message will be sent to the user." & vbCrLf &
"Please ensure you want to perform this action before hitting accept.",
My.Resources.Confirmation, RelayMessageOptions.Confirm_YesNo) =
DialogResult.Yes
How would I make that string into a resource?
In the standard VS resource manager (is this the manager you're using?) you can enter a multi-line string resource directly in the editor by using shift-Enter:
Note that this is actually stored as a string with CR+LF pairs, assisted by the space="preserve" attribute. Viewing the .resx file in a text editor:
Results using a standard message box:
MessageBox.Show(strings.myString)
I don't know how it is usually handled in globalization problems. But an easy way would be to define your own escape character formats. For example you could define \n as a newline character. When you actually use your ressource you could then use
If Not RelayMessage(Strings.Replace(myResourceString, "\n", vbCrLf),
My.Resources.Confirmation, RelayMessageOptions.Confirm_YesNo) =
DialogResult.Yes
instead of
If Not RelayMessage(myResourceString,
My.Resources.Confirmation, RelayMessageOptions.Confirm_YesNo) =
DialogResult.Yes
Or you could manually add chars with character codes 10 and 13 (e.g. ChrW(10) & ChrW(13)) at the vbCrLf location in your ressource string. This equals a vbCrLf (meaning a carriage return (10) + line feed (13)). This would avoid manipulation of the source code. Other stuff like Tab (9) have codes, too. These are called control characters. Take a look at the wikipedia http://en.wikipedia.org/wiki/Control_character

FileSystem.WriteAllText adds non-printable characters

Here are two methods for writing text to a file in VB.Net 2012. The first one prepends the same three non-printable characters to each file: . The second one works as expected and does not add the three characters. objDataReader is an OleDB datareader.
Any idea why?
Greg
My.Computer.FileSystem.WriteAllText(lblLocation.Text & "\" &
objDataReader("MessageControlId").ToString & ".txt", objDataReader("MsgContents").ToString, False)
Using outfile As New StreamWriter(lblLocation.Text & "\" & objDataReader("MessageControlId").ToString & ".txt")
outfile.Write(objDataReader("MsgContents").ToString)
End Using
Thanks. I found the entry below I after Googled BOM, in case anyone wants a more detailed explanation. While the BOM was not visible in a text editor it did cause problems when I passed the file to our HL7 interface engine.
Greg
Write text files without Byte Order Mark (BOM)?

Reading .txt file

I am using following code to read text from a .txt file. But I don't know how to
perform search within file and how to read a specific line in the text file, based on search.
Dim vrDisplay = My.Computer.FileSystem.ReadAllText(CurDir() & "\keys.txt")
MsgBox(vrDisplay)
For an example,
if I want to read the line that contains the word "Start", how to do that
Thanks.
Instead of reading all text, for efficiency's sake,
Open a FileStream for the file in question.
Create a StreamReader.
Loop through, calling ReadLine until either you find the end of the file, or the string contains "Start".
Edit: even if it's required that you keep the entire file in memory, you can still do the above by using a MemoryStream().
It isn't easy to tell from your post if it's the best possible solution, but one solution would be to use regular expressions to find all lines containing the word Start:
^.*\bStart\b.*$
matches an entire line that contains the complete word Start anywhere. It rejects Start as a part of a word, for example Starting won't be matched (that's what the \b word boundary anchors are for).
To use this in VB.NET:
Dim RegexObj As New Regex(
"^ # Start of line" & chr(10) & _
".* # Any number of characters (anything except newlines)" & chr(10) & _
"\b # Word boundary" & chr(10) & _
"Start # ""Start""" & chr(10) & _
"\b # Word boundary" & chr(10) & _
".* # Any number of characters (anything except newlines)" & chr(10) & _
"$ # End of line",
RegexOptions.Multiline Or RegexOptions.IgnorePatternWhitespace)
AllMatchResults = RegexObj.Matches(vrDisplay)
If AllMatchResults.Count > 0 Then
' Access individual matches using AllMatchResults.Item[]
Else
' Match attempt failed
End If