Posts Tagged ‘C#’

Escaping backslash character in C# .NET MySQL-queries

Wednesday, March 12th, 2008

Using escape-sequences like \t or \n is one thing, but escaping the escapecharacter (often ‘\’) can sometimes be a pain… This is especially true when the string you’re escaping is about to be processed by several succeeding processes, like: 1) a compiler, 2) a regex-engine, 3) a database, … , etc.

Anyways, I’ve experimented some with MySql-queries from within C# .NET, using Windows paths (containing backslashes as path separators) in the WHERE-clauses. We have a query of one of the forms:

case 1: = operator

querystring1 =
  "SELECT a,b,path FROM table " +
  "WHERE path = '" + patharg1 + "';";

or

case 2: LIKE operator

querystring2 =
  "SELECT a,b,path FROM table " +
  "WHERE path LIKE '" + patharg2 + "';";

Here is what I’ve found out:

case 1: = operator
Use 4 backslashes for each backslash in the saved record you’re matching against. You could do:

patharg1 =
  patharg1.Replace("\\", "\\\\");

(The 2 backslashes in the first replace-argument is for escaping the backslash within the compiler.)

case 1: LIKE operator
Use 8(!) backslashes for each backslash in the saved record you’re matching against. You could do:

patharg2 =
  patharg2.Replace("\\", "\\\\\\\\");

(The 2 backslashes in the first replace-argument is for escaping the backslash within the compiler.)

The two cases could then look like this:

case 1:

querystring1 =
  "SELECT a,b,path FROM table " +
  "WHERE path = 'c:\\\\some\\\\path.txt';";

case 2:

querystring2 =
  "SELECT a,b,path FROM table " +
  "WHERE path LIKE 'c:\\\\\\\\some\\\\\\\\path.txt';";

The above is if you put the querystring into, for instance, a MySqlCommand’s CommandText.

However, if you use datasets and run something like

dataTable.Select(filterExpression)

where dataTable is a DataTable instance and filterExpression is a string, you must not escape the backslash more than for a usual string (you’ll just write “\\” or @”\”, because some kind of escape of the backslash is always necessary for the compiler).

Note to self: C# and logical shortcircuiting

Monday, March 10th, 2008

C# (.NET) do short-circuit logical expressions; i.e.:

1)

(A || B)

==> If A is true, then only A is evaluated.

2)

(C && D)

==> If C is false, then only C is evaluated.

This means that, provided that A is true, expression 1 is true even though B would throw an exception if evaluated.

An example use of expression 2:


if ((filename != "") && (new FileInfo(filename).Exists))
	//file exists

If filename == “”, the Exists-statement would throw an exception. However, since the first expression (…!=…) is false, the Exists-statement is never evaluated, and the exception doesn’t occur.