Jay Zee
Jay Zee

Reputation: 263

How can I get all filenames without path in c#

I am using this code

string[] filePaths = Directory.GetFiles(Server.MapPath("~/Gallery/GalleryImage/" + v));
foreach (string item in filePaths)
{
    Response.Write(item);
}

Problem in this code i am getting file name with full path like this

C:\Users\AGENTJ.AGENTJ-PC\Documents\Visual Studio 2010\WebSites\mfaridalam\Gallery\GalleryImage\c050\DSC_0865.JPG

I just want file which is "DSC_0865.JPG"

Upvotes: 1

Views: 4163

Answers (4)

Chris M.
Chris M.

Reputation: 1841

This is pretty straight forward:

string[] filePaths = Directory.GetFiles(Server.MapPath("~/Gallery/GalleryImage/" + v));
foreach (string item in filePaths)
{
    Response.Write(System.IO.Path.GetFileName(item));
}

Upvotes: 0

Max
Max

Reputation: 156

You could use the methods in the Path such as GetFileName if you just want the bit without the path.

In your case something like:

foreach(string item in filePaths)
{
      Response.Write(Path.GetFileName(item));
}

Upvotes: 0

Douglas
Douglas

Reputation: 54887

You can use the Path.GetFileName method to get the file name (and extension) of the specified path, without the directory:

foreach (string item in filePaths)
{
     string filename = Path.GetFileName(item);
     Response.Write(filename);
}

Upvotes: 11

It'sNotALie.
It'sNotALie.

Reputation: 22794

Try using Path.GetFileName:

Directory.GetFiles(Server.MapPath("~/Gallery/GalleryImage/" + v))
         .Select(Path.GetFileName);

Upvotes: 6

Related Questions