0

Situation: I've been trying to get picture from database and put it on picturebox. Database was BLOB type. I tried the methods given to me (How to retrieve image from database and paste to picturebox?), and sadly nothing worked. So, instead of BLOB, I decided to use string and get the full path of the image.

Problem: The slashes are gone. Database example

Code:

private void pbox1_Click(object sender, EventArgs e)
    {
        OpenFileDialog rest = new OpenFileDialog();

        rest.Filter = "images| *.JPG; *.PNG; *.GIF";

        if (rest.ShowDialog() == DialogResult.OK)
        {
            pbox1.Image = Image.FromFile(rest.FileName);

            filename = Path.GetFullPath(rest.FileName);

        }

    }

I insert it into database ("filename" is a global variable):

   MySqlCommand comm = new MySqlCommand("INSERT INTO casestudyprofile(lastname, firstname, birthdate, status, caseage, program, dateJoined, picture, address) VALUES('" + lname + "', '" + fname + "', '" + dtbirth.Value.Date.ToString("yyyyMMdd") + "','" + status + "','" + age + "','" + program + "','" + dtjoin.Value.Date.ToString("yyyy/MM/dd") + "', '" + filename + "', '" + address + "')", conn);

Then I call it like this:

   pbox2.ImageLocation = dt.Rows[0]["picture"].ToString();

I found out it won't work because the full path stored in database have their slashes removed. I manually put them in the database and it worked. But, how in code? Any help is greatly appreciated.

N. Tanaka
  • 37
  • 8
  • 4
    Your code is vulnerable. Don't concatenate queries together. https://stackoverflow.com/questions/7505808/why-do-we-always-prefer-using-parameters-in-sql-statements probably might have something to do with your problem as well. –  Aug 10 '17 at 12:38
  • inspect what `GetFullPath` method returns. also, avoid global variable `filename` and use parameters to inject values into query. – tchelidze Aug 10 '17 at 12:40
  • 3
    You need to escape your backslashes. https://dev.mysql.com/doc/refman/5.7/en/string-literals.html – Harsh Aug 10 '17 at 12:41
  • @Will I'm still learning C# so SQL injection prevention is still far from me. However, I'll try incorporating it to my program if I finish the "draft". Thank you. – N. Tanaka Aug 10 '17 at 15:49
  • @Harsh Thanks! Now I understand why Artemis' answer worked. – N. Tanaka Aug 10 '17 at 15:51
  • Also, in future, add the database type as well. Most people will assume sql server if you're working in C#. –  Aug 10 '17 at 16:07

1 Answers1

0

filename = Path.GetFullPath(rest.FileName).Replace("\", "\\");

Artemis
  • 413
  • 3
  • 10
  • 24