简体   繁体   English

如何在C#中获取没有路径的所有文件名

[英]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" 我只想要“ DSC_0865.JPG”文件

You can use the Path.GetFileName method to get the file name (and extension) of the specified path, without the directory: 您可以使用Path.GetFileName方法获取指定路径的文件名(和扩展名),而无需目录:

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

Try using Path.GetFileName : 尝试使用Path.GetFileName

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

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));
}

You could use the methods in the Path such as GetFileName if you just want the bit without the path. 如果只希望位不包含路径,则可以使用Path的方法,例如GetFileName

In your case something like: 在您的情况下,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM