Sunday, April 13, 2008
After reading A post by Sergio Pereira I thought about translating his code to VB.Net because as usual all the cool things are written in C#.
So this piece
    using(StreamReader rd = File.OpenText("Data.txt"))  
{
string line = rd.ReadLine();
while(line != null)
{
DoSomething(line);
// do more stuff with the line text

//move on
line = rd.ReadLine();
}
}
Becomes

Dim rd As System.IO.StreamReader = System.IO.File.OpenText("Data.txt")
Using (rd)

Dim line As String = rd.ReadLine()
While (line IsNot Nothing)

dosomething(line)
' do more stuff with the line text

'move on
line = rd.ReadLine()
End While
End Using

and the next bit

    public static class FileUtil  
{
public static void EachLine(string fileName, Action<string> process)
{
using(StreamReader rd = File.OpenText(fileName))
{
string line = rd.ReadLine();
while(line != null)
{
process(line);
line = rd.ReadLine();
}
}
}
}

will translate in

Public Class FileUtil

Public Shared Sub EachLine(ByVal fileName As String, ByVal process As Action(Of String))
Dim rd As System.IO.StreamReader = System.IO.File.OpenText(fileName)
Using (rd)

Dim Line As String = rd.ReadLine()
While (Line IsNot Nothing)

process(Line)
Line = rd.ReadLine()
End While
End Using
End Sub
End Class

And we call that last piece of code like this

FileUtil.EachLine("Data.txt", AddressOf dosomething)

The doSomething method would look something like this

Private Sub dosomething(ByVal line As String)
        MessageBox.Show(line)
    End Sub


And that's it.



4/13/2008 9:59 PM Romance Daylight Time  #    Disclaimer  |  Comments [0]  |  Trackback