I wish to include a file path in an SQL Server query which is executed from C#. The file path is obtained from a textBox, which in turn was provided by an open file dialog. The SQL server query is contained in the following string:
string strSqlAcctSelect = String.Format("SELECT Code AS dhAccountType,
Name as dhAcctName
INTO {0} " + "FROM OPENROWSET('Microsoft.Ace.OLEDB.12.0', 'Excel 8.0; DATABASE =
{1}', 'SELECT * FROM " + "[Sheet1$]')", strAcctTabName, this.textBoxAcctPath.Text);
Where at runtime:
this.textBoxAcctPath.Text = "J:\\CCCDataVic\\RMH\\PE1006Data\\DHCC.xls";
When this string is parsed back to screen of course the file path string looks as it should: ‘J:\CCCDataVic\RMH\PE1006Data\DHCC.xls’.
The problem is this: how do I include a string containing a path in an SQL Query in C# (as above) using the literal “\” (single back slash) without parsing the query “\” (the double back slash)?
Whatever you do, the string is parsed to SQL containing the double back slash which SQL doesn’t like.
Try this
But this would throw exception if you supply invalid path, so I advise you to use below code