It could be the case that the code slowness is due to the wildcard search on all files: (e.g. di.GetFiles takes too long)
Too many files in your top folder/subfolders.
The network connection is too slow to fetch file information or photos are too big. (remote directory access could be slow - you can check by copying a big file say 1GB to your remote directory and copy back to your PC)
The photos may be stored with different aspect ratios to your picture box size. (Rendering takes a while if resizing needs to happen)
For starters, let us assume your folder has too many files (1000s), then we need to do a smarter search for the first file folder by folder:
string baseFolder = @"\\\\jun01\\hr\\photo";
string imgName = "*" + textBoxEmplNo.Text + "*.jpg";
var file = FindFirstFile(baseFolder, imgName);
if (!string.IsNullorEmpty(file))
{
pictureBox1.Visible = true;
pictureBox1.Image = Image.FromFile(file);
}
else
{
pictureBox1.Visible = true;
pictureBox1.Image = Image.FromFile(@"\\\\jun01\\hr\\photo\\No-image-found.jpg");
}
where FindFirstFile is taken from Markus's answer as:
public static string FindFirstFile(string path, string searchPattern)
{
string[] files;
try
{
// Exception could occur due to insufficient permission.
files = Directory.GetFiles(path, searchPattern, SearchOption.TopDirectoryOnly);
}
catch (Exception)
{
return string.Empty;
}
if (files.Length > 0)
{
return files[0];
}
else
{
// Otherwise find all directories.
string[] directories;
try
{
// Exception could occur due to insufficient permission.
directories = Directory.GetDirectories(path);
}
catch (Exception)
{
return string.Empty;
}
// Iterate through each directory and call the method recursivly.
foreach (string directory in directories)
{
string file = FindFirstFile(directory, searchPattern);
// If we found a file, return it (and break the recursion).
if (file != string.Empty)
{
return file;
}
}
}
return string.Empty;
}