Display the text file contents found in list

Display the text file contents found in listbox

This code will display the filenames found under the directory mentioned and

on click of the text filename the contents of the file will be displayed.

1. In a .aspx file drag and drop Listbox,Label and a Textbox with textMode set to multiline.

<h2><b>Display the text file contents</b></h2>
<form id="form1" runat="server">
<td style="width: 102px">
<asp:ListBox ID="lstFiles" AutoPostBack="true" runat="server"
Height="150px" Width="200px"
OnSelectedIndexChanged="lstFiles_SelectedIndexChanged" BackColor="AliceBlue"/>
<asp:Label ID="Label1" runat="server"></asp:Label><br />
<asp:TextBox ID="txtContent" TextMode="MultiLine"
runat="server" Height="115px" Width="374px" BackColor="AliceBlue"></asp:TextBox>

2.Code to be included in code behind.

using System;
using System.Data;
using System.IO;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class textdisplay : System.Web.UI.Page
string FilePath;
//declare the Streamreader object.
StreamReader objStreamReader = default(StreamReader);

protected void Page_Load(object sender, EventArgs e)
string[] FileEntries = null;
string FileName = null;
//counters is the directory name where in the text files are resided.
FilePath = Server.MapPath("~/counters/");
FileEntries = Directory.GetFiles(FilePath);
if (!Page.IsPostBack)
foreach (string file1 in FileEntries)
FileName = Path.GetFileName(file1);

protected void lstFiles_SelectedIndexChanged(object sender, System.EventArgs e)

public void ReadTextFile()
objStreamReader = File.OpenText(FilePath + lstFiles.SelectedItem.Value);
string textFileContent = objStreamReader.ReadToEnd();
txtContent.Text = textFileContent;


Reference: http://aspnet101.com/codesample.aspx?code=getandreadfiles



Author: Umesh Bhosale26 Mar 2014 Member Level: Silver   Points : 0

You can also provide filter to getFile()

e.g. Directory.GetFiles("D:\\Test","*.xml");
It will get only Xml files if any

Umesh Bhosale

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: