Reputation: 13
I am trying to do a String.Split on VB.NET and it doesn't appear to work. Appreciate any help to see what I am missing:
In C#:
sFileContents = File.ReadAllText(f.FullName);
sLines = sFileContents.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
In VB.NET:
sFileContents = File.ReadAllText(f.FullName)
sLines = sFileContents.Split(New String() {"\r\n"}, StringSplitOptions.RemoveEmptyEntries)
In C# I get the number of lines split correctly and in VB.NET I only get 1 line.
Thanks
Upvotes: 1
Views: 747
Reputation: 6251
Use this:
sFileContents = File.ReadAllText(f.FullName)
sLines = sFileContents.Split({ Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
Also, note that New String()
is omitted in the code above. VB.NET can directly accept arrays in the form { <element>, <element> }
. So no need for the New
keyword and the initializer.
You should, in fact use Environment.NewLine
as you can never be certain about line-endings on different platforms.
In VB.NET, "\r\n"
is interpreted as "\r\n"
itself and not a Carriage-Return + NewLine
as with C#. They are called special characters. VB.NET doesn't have any. It's only the double quotes which need escaping (by using pairs). For Example:
Dim result = "He said, ""This is some code.""" 'Yields : He said, "This is some code."
Another option would be to use predefined VB.NET constants like vbCrLf
but I would say that Environment.NewLine
is a better way.
Upvotes: 1
Reputation: 10304
Escape sequences don't work in VB.NET.
You should use the VB.NET constants: vbCrLf, vbLf
sFileContents = File.ReadAllText(f.FullName)
Dim arg() As String = {vbCrLf, vbLf}
sLines = sFileContents.Split(arg, StringSplitOptions.RemoveEmptyEntries)
Upvotes: 1