2

Hi I want to get only name of the files from a folder without the full path. Here is my code so far (asp.net)

    string[] files = Directory.GetFiles(Server.MapPath("~/Files/"));      

    List<string> filenames = new List<string>();
    for (int i = 0; i < files.Length; i++)
    {
        filenames.Add(files[i]);             
    }
    GridView1.DataSource = filenames;
    GridView1.DataBind();

How would I accomplish this in asp.net Thanks again

3 Answers 3

3

Try this

string[] files = 
Directory.GetFiles(Server.MapPath("~/Files/")).Select(fi => Path.GetFileName(fi);

Also add reference to this

using System.Linq;
Sign up to request clarification or add additional context in comments.

2 Comments

Hi rs thanks to you but I am getting an Error 'string[]' does not contain a definition for 'Select' and no extension method 'Select' accepting a first argument of type 'string[]' could be found (are you missing a using directive or an assembly reference?)
You probably don't have a reference to System.Linq.
1

Try using

filenames.Add(Path.GetFileName(files[i]));

1 Comment

Thanks Kremena Lalova. You just solved my issue. You made it so easy thanks again.
1

Try DirectoryInfo.GetFiles.

This will return an array of FileInfo which will give you what you want and more.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.