3

I am trying to save a image directory that a user opened into a database. But the symbol "\" is not in the path. It is turning out like C:UsersAshleyDesktopScreenshot_1.png and as you can see it has no \, which make it an invalid path.

private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog open = new OpenFileDialog();
        if (open.ShowDialog() == DialogResult.OK)
        {
            pictureBox1.Image = Image.FromFile(open.FileName);
            pictureBox2.Image = Image.FromFile(open.FileName);
            MySQL.ExecuteNonQuery(@"UPDATE users SET profile_image_dir = '" + open.FileName + "' WHERE username = '" + User.Details.Username + "'");
            MessageBox.Show(""+ open.FileName + "\r\n");
        }

On the MySQL.ExecuteNonQuery i am saving it to the database and it is turning out like as i showed before

celerno
  • 1,367
  • 11
  • 30
user3354197
  • 95
  • 2
  • 11
  • 1
    +1 for parameterized queries. But still I think you can just `open.File.Replace("\", "\\");` right before `MySQL.ExecuteNonQuery` – Leron Feb 26 '14 at 23:34

2 Answers2

4

A parameterized query should work

string cmdText = @"UPDATE users SET profile_image_dir = @file
                   WHERE username = @uname";

using(MySqlConnection cn = new MySqlConnection(.....))
using(MySqlCommand cmd = new MySqlCommand(cmdText, cn))
{
   cn.Open();
   cmd.Parameters.AddWithValue("@file", open.FileName);
   cmd.Parameters.AddWithValue("@uname", User.Details.Username);
   cmd.ExecuteNonQuery();
}
Steve
  • 213,761
  • 22
  • 232
  • 286
0

Use a parameterized query. Doing so is safer and will help avoid other potential problems.

That being said, you can also look at the MySql documentation on string literals and you'll see how it handles a backslash to see what it's doing with your literal string.

Community
  • 1
  • 1
McAden
  • 13,714
  • 5
  • 37
  • 63