1

Hi I have something like the code below, I want to sort/order the files in the folder lets say by name of the file in asc or dsc order, before binding to the gridview:

string[] filePaths = Directory.GetFiles(Server.MapPath("~/Uploads/"));
                    List<ListItem> files = new List<ListItem>();

                foreach (string filePath in filePaths)
                {
                    files.Add(new ListItem(Path.GetFileName(filePath), filePath));
                }
           
                GridView1.DataSource = files;
                GridView1.DataBind();
skofi
  • 65
  • 10

1 Answers1

2

You can simply order by after foreach loop

 files = files.OrderBy(x => x.Text).ToList();

For Order by descending

files = files.OrderByDescending(x => x.Text).ToList();
Hammad Shabbir
  • 722
  • 1
  • 6
  • 13
  • thank you. If I wanted now to order them by last modified how that would be possible? – skofi Jan 11 '21 at 18:28
  • You need to get last modified time for each file and then sort it https://stackoverflow.com/questions/3360324/check-last-modified-date-of-file-in-c-sharp – Hammad Shabbir Jan 11 '21 at 18:29