How to run through all the files within a folder and list them in code.
List files to bulleted list
In this case we find all the files within the current folder except
csharp.aspx and populate a bulleted list with them as hyperlinks. The C Sharp index file uses this code to create the sample list.
1: using System.IO;
2: using System.Text.RegularExpressions;
3:
4: protected void Page_Load(object sender, EventArgs e)
5: {
6: DirectoryInfo di = new DirectoryInfo(MapPath(""));
7: FileInfo[] rgFiles = di.GetFiles("*.aspx");
8: string strFile = "";
9: foreach (FileInfo fi in rgFiles)
10: {
11: if (fi.Name.ToLower() != "csharp.aspx")
12: {
13: strFile = Regex.Replace(fi.Name.ToLower(), ".aspx", "");
14: blCsharp.Items.Add(new ListItem(strFile,fi.Name.ToLower()));
15: }
16: }
17: }
List files in dropdown list
In this case we list the number contained within a filename starting
with a certain country name. The images/chart fodler contains many
charts for different countries each with a numerical identifier As we
only need the numberical identifier to store in a database we strip out
the rest of the filename and list the charts as [chart #]
1: using System.IO;
2: using System.Text.RegularExpressions;
3:
4: protected void Page_Load(object sender, EventArgs e)
5: {
6: string strCountry = "country name";
7: string strChart = "";
8: DirectoryInfo di = new DirectoryInfo(MapPath("~/images/charts"));
9: FileInfo[] rgFiles = di.GetFiles(strCountry + "*.gif");
10: var slSortedList = new SortedList();
11:
12: foreach (FileInfo fi in rgFiles)
13: {
14: strChart = Regex.Replace(fi.Name.ToLower(), ".gif", "");
15: strChart = Regex.Replace(strChart, strCountry, "");
16: slSortedList.Add(strChart,"Chart " + strChart );
17: }
18: cboChart.DataSource = slSortedList;
19: cboChart.DataTextField = "Value";
20: cboChart.DataValueField = "Key";
21: cboChart.DataBind();
22: }
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5