在标签文本中显示文件名

Display File name in Label Text

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

例如位置是:C:\image\

标签应该说:

C:\image\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);
        }
    }

您不需要获取所有文件 (Directory.GetFiles),只需要 第一个 ,所以让我们摆脱[=16] =]数组并简化代码:

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