Click here to Skip to main content
15,897,518 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I'm writing a program to scan a folder for video files, parse it through the database, and then add it to the database if it dosn't exist. The following is the code to do the check.
foreach (string filename in openFileDialog.FileNames)
{
  if (dlg.FileName != "")
  {
    string FilePattern = "SELECT * FROM Table WHERE Path = \"" + filename + "\"";
    string FileExist = "NO";
    SqlCeConnection con;
    try
    {
      con = new SqlCeConnection();
      con.ConnectionString = "Data Source=" + DataDirectory + "\\FilePath.sdf";
      {
        con.Open();
        using (SqlCeCommand cmd = new SqlCeCommand(FilePattern, con))
        {
          using (SqlCeDataReader reader = cmd.ExecuteReader())
          {
            while (reader.Read())
            {
              FileExist = "YES";
              MessageBox.Show("Already exist");
            }
          }
        }
      }
    }
    catch (SqlException ex)
    {
      Console.Write(ex);
    }
    if (FileExist == "NO")
      Save(filename);
  }
}


Now the problem started when the filename had a single quote in it. It would simply not save the file because the single quote enables the SqlException. Is there a way to change the filename to allow filenames with (') in them to still run.
Posted

You need to use the escape character for the ' character - something like ''.
 
Share this answer
 
v3
Google for "parameterized sql .net" and you'll find tons of examples that show you how to do this properly and NOT use string concatentation like you've done in your snippet.
 
Share this answer
 
Comments
CLFQ85 16-Apr-11 0:53am    
Thanks. I found the solution at http://msdn.microsoft.com/en-us/library/ff648339.aspx. By simply adding .replace("'","''") to the end of filename in the FilePattern.
Dave Kreskowiak 16-Apr-11 8:48am    
It is A solution, not the correct solution. Using parameterized queries is far better because of SQL Injection attacks and their ability to format parameters correctly (such as a DateTime value) and escape characters that could screw up your query statements, such as the "'".

Seriously, get into the habit of using them NOW before you're forced to rewrite your code later.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900