【问题标题】:How to retrieve image if folders don't share the same base folder如果文件夹不共享相同的基本文件夹,如何检索图像
【发布时间】:2017-10-30 07:40:05
【问题描述】:

我是 C# 编程语言的新手。任何人都可以帮助我如何从 folder>folder>folder>image 的多个文件夹中检索图像。下面是我已经尝试过的代码,但它只在 folder>image 时检索图像。我已经尝试过这样的string baseFolder = @"\\\\egmnas01\\hr\\photo\\~";但仍然无法正常工作。请有人帮助我。谢谢。

    string baseFolder = @"\\\\egmnas01\\hr\\photo\\";
    string[] employeeFolders = Directory.GetDirectories(baseFolder);

    string imgName = textBoxEmplNo.Text +  ".jpg";
    bool fileFound = false;

    foreach (var folderName in employeeFolders)
    {
     var path = Path.Combine(folderName, imgName);
      if (File.Exists(path))
    {
      pictureBox1.Visible = true;
      pictureBox1.Image = Image.FromFile(path);
      fileFound = true;

    }

    }
      if (!fileFound)
    {

      pictureBox1.Visible = true;
      pictureBox1.Image = Image.FromFile(@"C:\Users\jun\Desktop\images\photo\No-image-found.jpg");
    }

【问题讨论】:

  • 您是否想在子目录树中查找名称与您提供的文件名匹配的任何文件?如果您不知道子目录,您可能需要这样的东西来查找匹配的文件:System.IO.Directory.GetFiles(@"c:\test\", "\\*.jpg", System.IO.SearchOption.AllDirectories);
  • @john 该代码替换此代码 string baseFolder = @"\\\\egmnas01\\hr\\photo\\"; ?因为我已经尝试过了,但还是不行。

标签: c# visual-studio-2013 windows-forms-designer


【解决方案1】:

我相信以下内容会对您有所帮助

static void Main(string[] args)
{
    // test path... replace with the path you need
    string baseFolder = @"D:\test\";

    string imgName = textBoxEmplNo.Text + ".jpg";
    bool fileFound = false;

    DirectoryInfo di = new DirectoryInfo(baseFolder);
    foreach (var file in di.GetFiles(imgName, SearchOption.AllDirectories))
    {
        pictureBox1.Visible = true;
        pictureBox1.Image = Image.FromFile(file.FullName);

        fileFound = true;
        break;
    }

    if (!fileFound)
    {

        pictureBox1.Visible = true;
        pictureBox1.Image = Image.FromFile(@"C:\Users\jun\Desktop\images\photo\No-image-found.jpg");
    }
}

请注意,在这个论坛中已经有类似的questions 已经询问(并已回答),也许是针对不同的文件(xml 而不是 jpg) 另外,当您第一次开始使用 .Net API 或感到困惑时,请参考MSDN

【讨论】:

  • 感谢您的帮助。但仍然无法检索图像。 :(
  • @Miza 是不是有一个名称匹配的文件,但上面的逻辑仍然没有找到它?请将di.GetFiles(...) 检索到的所有文件名打印到控制台/消息框。如果拨打了di.GetFiles("*.jpg", SearchOption.AllDriectories),您是否看到它至少列出了一些文件。您可以尝试使用类似的嵌套文件夹结构编写类似的示例,如果失败,请查看失败的地方。
  • 有必要static void Main(string[] args)吗?因为我是private void textBoxWorkNo_KeyUp(object sender, KeyEventArgs e)中的代码。
  • 您感兴趣的代码位于静态 void Main(...) 中。我编写了一个控制台应用程序来传达意图(我的答案)。你可以忽略 static void Main(...),只考虑里面的逻辑。
  • 非常感谢!经过努力,终于成功了:)。谢谢!
猜你喜欢
  • 2011-07-18
  • 1970-01-01
  • 2019-12-08
  • 1970-01-01
  • 1970-01-01
  • 2012-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多