Pages

Wednesday, January 11, 2012

Sample file import with StreamReader

Here is one example of how you can import files with .NET's StreamReader:
static void ImportWithStreamReader(Args _args)
{
    Filename                filename = @'C:\Temp\importme.txt';           
    System.IO.StreamReader  reader;
    System.String           line;
    InteropPermission       interopPermission;
   
    interopPermission = new InteropPermission(InteropKind::ClrInterop);
    interopPermission.assert();

    reader = new System.IO.StreamReader(filename, 
                                       System.Text.Encoding::get_UTF8());

    line = reader.ReadLine();

    while (!System.String::IsNullOrEmpty(line))
    {
        // Do something with line

        line = reader.ReadLine();
    }

    reader.Close();
    reader.Dispose();
}
If you can work with the file as on big chunk of text you can get away with just reading once, using the ReadToEnd method.

Read more about StreamReader on MSDN.

No comments: