Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

C#: Reading a File

📅 2010-Nov-21 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ csharp, files ⬩ 📚 Archive

using System;
using System.IO;

// Check if file exists
var fileName = "Foobar.txt";
if ( !File.Exists( fileName ) )
    return;

// Open file as stream
var file = new StreamReader( fileName );

// Read file line-by-line
String line;
while ( ( line = file.ReadLine() ) != null )
{
    // Split line by space delimiter
    var subStrArr = line.Split();

    // Iterate through substrings and process them
    for ( Int32 i = 0; i < subStrArr.Length; ++i )
        Console.WriteLine( subStrArr[ i ] );
}

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧