C# 循环遍历目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9142355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 06:09:09  来源:igfitidea点击:

Looping through a directory

c#asp.net.net

提问by sab669

I'm stuck trying to figure out how to print out the images I'm storing in a directory in ASP/C#

我一直在想如何打印出我存储在 ASP/C# 目录中的图像

I found this, but the problem is it prints out C:\\Visual Studios 2010\Projects\MyTestUploader\Files\img001.jpg

我找到了这个,但问题是它打印出 C:\\Visual Studios 2010\Projects\MyTestUploader\Files\img001.jpg

string[] fileEntries = Directory.GetFiles(sourceDir);
foreach (string fileName in fileEntries)
{
Label1.Text += "<img src=\"" + fileName + "" /><br />";
}

For now I just want to simply print out all the images in the directory. I'll worry about formatting them nicely, later :)

现在我只想简单地打印出目录中的所有图像。稍后我会担心如何很好地格式化它们:)

回答by Douglas

You can use Path.GetFileNameto get the file name and extension of the specified path, whilst excluding the directory path (which is presumably what you want).

您可以使用Path.GetFileName获取指定路径的文件名和扩展名,同时排除目录路径(这大概是您想要的)。

string[] fileEntries = Directory.GetFiles(sourceDir);
foreach (string fileName in fileEntries)
{
    Label1.Text += "<img src=\"" + Path.GetFileName(fileName) + "\" /><br />";
}

For example, calling

例如,调用

Path.GetFileName(@"C:\Visual Studios 2010\Projects\MyTestUploader\Files\img001.jpg")

would return "img001.jpg".

会回来"img001.jpg"

Note that you were also missing a \to escape the "at the end of your attribute value.

请注意,您还缺少 a\来转义"属性值的末尾。

回答by Andrey Morozov

Try using the Directory.GetFiles(sourceDir, "*.jpg");

尝试使用 Directory.GetFiles(sourceDir, "*.jpg");