C# Read File Content
Posted by in CSharp December 29, 2011 Leave a comment

This post is simple a function and example on How to read content of a text file by using C#. This file could be .txt, .xml, .log which is generated by your application/web for caching or storing user information or parsing data used in your application.

In function below, we need to use System.IO namespace to utilize functions in FileStream and StreamReader classes. Also we need to use the MapPath method to get the physical path of the file we want to read its content.

Read File Content With C#

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
 
public partial class read_file : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string filename = "Hehe.htm";
        Response.Write(ReadFromFile(filename));
    }
 
    public static string ReadFromFile(string filename)
    {
        filename = HttpContext.Current.Server.MapPath(filename);
 
        string s = "";
        try
        {
            FileStream file = new FileStream(filename, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(file);
            s = sr.ReadToEnd();
            sr.Close();
            file.Close();
        }
        catch
        {
            s = "";
        }
        return s;
    }
}

Hoan Huynh is the founder and head of 4rapiddev.com. Reach him at hoan@4rapiddev.com