Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the aspx files collection from my project

Tags:

c#

How can I read all my aspx file names that I have into my project? I need to get the collection of my aspx files.

I want to add them into a DropDownList.

Like

foreach(ASPX file in myProject.aspx.collections) {
  dropdownlist1.Items.Add(file.name);//Name could be: Default.aspx
}

Thanks in advance.

Edit: Thank you friends, really all your answers were correct. Finally I did it as next:

string sourceDirectory = Server.MapPath("~/");
DirectoryInfo directoryInfo = new DirectoryInfo(sourceDirectory);
var aspxFiles = Directory.EnumerateFiles(sourceDirectory, "*.aspx", SearchOption.TopDirectoryOnly).Select(Path.GetFileName);

foreach (string currentFile in aspxFiles) {
    this.dropdownlist1.Items.Add(currentFile);
}
like image 955
Poyson1 Avatar asked Oct 24 '25 02:10

Poyson1


2 Answers

With reflection, this should work:

public static IEnumerable<string> getAspxNames()
{
    var pageTypes = Assembly.GetExecutingAssembly().GetTypes()
        .Where(t => t.BaseType == typeof(Page));
    return pageTypes.Select(t => t.Name).ToList();
}

// ...
foreach(string pageName in getAspxNames())
    dropdownlist1.Items.Add(pageName + ".aspx");
like image 186
Tim Schmelter Avatar answered Oct 26 '25 17:10

Tim Schmelter


Try this:

var dirPath = Server.MapPath("~/");
var ext = new List<string> {".aspx"};
var fileList = Directory.GetFiles(dirPath, "*.*", SearchOptions.AllDirectories)
     .Where(s => ext.Any(ex => s.EndsWith(ex));

dropdownlist1.DataSource = fileList;
dropdownlist1.DataBind();

For only file names do this

foreach(string file in fileList)
 dropdownlist1.Items.Add(Path.GetFileName(file));
like image 31
rs. Avatar answered Oct 26 '25 16:10

rs.