[英]Directory.GetFiles() returns full path
I want to return the files that are images, inside a particular directory. 我想返回特定目录内的图像文件。 I want to create the image path like this
我想这样创建图像路径
string[] ImageNames = Directory.GetFiles(path);
string tds="";
for (int i = 0; i < ImageNames.Length; i++)
{
tds += "<tr> <td> <img href=/Articles/ArticleImageStore/'" + ImageNames[i] + "' width='64' height='64'></img></tr> </td>";
}
but it returns the physical path of the file on the disk. 但它返回磁盘上文件的物理路径。 How should I do this??
我应该怎么做?
You can use Path.GetFileName
: 您可以使用
Path.GetFileName
:
string[] ImageNames = Directory.GetFiles(path)
.Select(p => Path.GetFileName(p)).ToArray();
This will produce a list with only the names of the files. 这将产生仅包含文件名的列表。
Rather than using the Directory
class I would use DirectoryInfo
then you can do this; 您可以使用
DirectoryInfo
而不是使用Directory
类,而是可以这样做。
string[] fNames = new DirectoryInfo(dirPath).GetFiles("*.png").Select(x => x.FileName).ToArray();
The DirectoryInfo
version of GetFiles returns FileInfo objects rather than the file paths as strings so you can do a lot more the with the results. GetFiles的
DirectoryInfo
版本以字符串形式返回FileInfo对象而不是文件路径,因此您可以对结果做更多的事情。 I happen to have a select which sort of nullifies that by just projecting a the FileName for each FileInfo instance returned by GetFiles but if you needed to do more with the files you could remove that then loop over the FileInfo objects. 我碰巧有一个选择,通过为GetFiles返回的每个FileInfo实例投影一个FileName来使该类无效,但是如果您需要对文件做更多操作,则可以删除该文件,然后遍历FileInfo对象。
Also, I'm using an overload that has a pattern which will make it easy to ignore your non image files. 另外,我使用的过载具有一种模式,可以很容易地忽略非图像文件。
DirectoryInfo docs; DirectoryInfo文档; http://msdn.microsoft.com/en-us/library/8he88b63.aspx
http://msdn.microsoft.com/zh-CN/library/8he88b63.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.