Read All Text Files in a Folder and Merge Into an aspx Page





Prabhakar_9345_Image1.jpg

In this article I am gathering all text files from a folder and merging them into a single aspx page. In this article I am using 45 text files; they are first read then combined into an aspx page; it's a fast way to assemble all files into a webpage.

In the aspx Page

First add this namespace:

System.IO

On Page Load Event

Then write this code for the Page Load:

protected void Page_Load(object sender, EventArgs e)
    {
       
        DirectoryInfo dirinfo = new DirectoryInfo(Server.MapPath("TXTF/"));

        string validExtensions = "*.txt";
        string[] extFilter = validExtensions.Split(new char[] { ',' });
        ArrayList files = new ArrayList();

        foreach (string extension in extFilter)
        {           
            files.AddRange(dirinfo.GetFiles(extension));
            try
            {
                for (int i = 0; i < files.Count; i++)
                {
                    StreamReader fb;
                    string filename = files[i].ToString();
                    fb = File.OpenText(dirinfo +  filename);
                    string input = null;
                    while ((input = fb.ReadLine()) != null)
                    {
                     Response.Write(input + "</br>");                                             
                    }
                    fb.Close();
                    //return 0;
                }
                               
            }
            catch (Exception ex)
            {
                lblerror.Text = ex.ToString();

            }

        }

Whole Setup....

All the text files are in a TXTF folder. In the aspx page you can change the folder name, then if you want to fetch only one file you can comment out the loop ... But this code works really well....

Conclusion

In this article I am showing how to merge multiple text files into one webpage. I think it is helpfull for every one....
 

Up Next
    Ebook Download
    View all
    Learn
    View all