如何在dir中添加图像中的每个文件名(查看代码)

时间:2013-02-11 01:40:34

标签: c# image path label

我想显示调试目录中的所有图像。文件名也是标签。

我唯一的问题是从每张图片的路径显示文件名。它只加载1个文件名

        int x = 0;
        int y = 0;
        string[] images = Directory.GetFiles(@"images");
        foreach (string image in images)
        {
            PictureBox PB = new PictureBox();
            PB.Image = new Bitmap(image);
            PB.SizeMode = PictureBoxSizeMode.CenterImage;
            PB.Size = new Size(250, 180);
            PB.Location = new Point(x, y);
            panel1.Controls.Add(PB);
            x += 260;
        }
        int a = 0;
        int b = 0;

        string names = System.IO.Path.GetFileName(@"images");
        foreach (string name in names)
        {
            Label label1 = new Label();
            label1.Text = name;
            label1.Location = new Point(a, b);
            this.Controls.Add(label1);
            a += 20;
        }

2 个答案:

答案 0 :(得分:0)

private void Form1_Load(object sender, EventArgs e)
{
    int x = 0;
    int y = 0;
    string[] images = Directory.GetFiles(@"images");
    foreach (string image in images)
    {
        PictureBox PB = new PictureBox();
        PB.Image = new Bitmap(image);
        PB.SizeMode = PictureBoxSizeMode.CenterImage;
        PB.Size = new Size(250, 180);
        PB.Location = new Point(x, y);
        panel1.Controls.Add(PB);
        x += 260;

        Label label1 = new Label();
        label1.Text = Path.GetFileName(name);
        label1.Location = new Point(a, b);
        this.Controls.Add(label1);
        a += 20;
    }

}

答案 1 :(得分:0)

我认为你不需要2个循环,你可以抓住文件名并在第一个循环中创建标签,

类似的东西:

int x = 0;
string[] images = Directory.GetFiles(@"C:\StackOverflow\New Folder");
foreach (string image in images)
{
    Panel item = new Panel();
    item.AutoSize = true;
    item.Location = new Point(x, 0);


    PictureBox PB = new PictureBox();
    PB.Image = new Bitmap(image);
    PB.SizeMode = PictureBoxSizeMode.CenterImage;
    PB.Size = new Size(250, 180);

    Label label1 = new Label();
    label1.Text = System.IO.Path.GetFileName(image);
    label1.Location = new Point(0, 90);
    label1.Width = 250;
    label1.TextAlign = ContentAlignment.MiddleCenter;

    item.Controls.Add(label1);
    item.Controls.Add(PB);

    panel1.Controls.Add(item);
    x += 260;

}

结果enter image description here