在标签文本中显示文件名

时间:2015-10-27 15:42:54

标签: c# .net winforms file picturebox

我正在使用WinForms。在我的表格中,我有一个picturebox。在表单加载时,我的应用程序从计算机内的特定文件夹打开png图片。我希望能够在标签中显示文件名。

例如,位置为:C:\image\

标签应该说:

  

C:\图像\ MyPicture.png

    private void Form1_Load(object sender, EventArgs e)
    {

        try // Get the tif file from C:\image\ folder
        {
            string path = @"C:\image\";
            string[] filename = Directory.GetFiles(path, "*.png");

            pictureBox1.Load(filename[0]);


            lblFile.Text = path; //I've tried this... does not give file name

        }
        catch(Exception ex)
        {
            MessageBox.Show("No files or " + ex.Message);
        }
    }

1 个答案:

答案 0 :(得分:1)

您无需获取所有文件(Directory.GetFiles),只需 1st one ,所以让我们摆脱数组并简化代码:

private void Form1_Load(object sender, EventArgs e)
{

    try // Get the tif file from C:\image\ folder
    {
        string path = @"C:\image\";
        String filename = Directory.EnumerateFiles(path, "*.png").FirstOrDefault();

        if (null != filename) {
          // Load picture 
          pictureBox1.Load(filename);
          // Show the file name
          lblFile.Text = filename;
        }
        else {
          //TODO: No *.png files are found
        } 
    }
    catch(IOException ex)
    {
        MessageBox.Show("No files or " + ex.Message);
    }
}