Image.FromFile will open a path, but not a string containing same path?

zck17 picture zck17 · Jan 12, 2012 · Viewed 8.3k times · Source
// The following line works.
imagebox.Image = Image.FromFile("C:/Users/Admin/Desktop/apps/pic1.png");

// The following line does not work.
imagebox.Image = Image.FromFile(imgPath);

// the test Text Box displays "C:/Users/Admin/Desktop/apps/pic1.png", exactly like in the first line
test.Text = imgPath;

When i click the button that is supposed to change the picturebox's image, i get an error basically saying illegal characters in path, and ArgumentException was unhandled

sorry for not doing that the first time.

k so the actual filename is being entered into a text box. I'm then converting that text into a string, and adding it to the begging and end to create a full file path.

string path = "\"C:/Users/Admin/Desktop/apps/";
string ext1 = ".png\"";


ID = idBox.Text;
imgPath = path + ID + ext1;
try
{
    imagebox.Image = Image.FromFile(imgPath);
}
catch (System.IO.FileNotFoundException)
{
    MessageBox.Show("Invalid Student or Faculty ID.");
}

Answer

Eric Rahm picture Eric Rahm · Jan 12, 2012

Just a guess, but if the text box literally displays:

"C:/Users/Admin/Desktop/apps/pic1.png"

Then you have quotes in your path, which is bad. In your code you use the quotes to define a string, if you're grabbing input from a user you don't need the quotes.