Search code examples
c#postgresqlvisual-studio-2010npgsql

NpgSQL insert file path containing backslashes "\\"


I am trying to create a record containing the path to a file. The insertion is done into a Postgres database where UTF8 is enabled, using the NpqSQL driver.

My table definition:

CREATE TABLE images
(
    id serial,
    file_location character varying NOT NULL
)

My SQL statement including the code that executes it (boiled down to a minimum):

string sqlStatement = "INSERT INTO images (file_location) VALUES ('\\2010')";

NpgsqlConnection dbConnection = new NpgsqlConnection(connectionString);
dbConnection.Open();
NpgsqlCommand dbCommand = new NpgsqlCommand(sqlStatement , dbConnection);
int result = dbCommand.ExecuteNonQuery();
dbConnection.Close();    

When using pgAdmin to insert the above statement, it works fine. Using the NpgSQL driver through Visual Studio C#, it fails with this exception:

"ERROR: 22021: invalid byte sequence for encoding \"UTF8\": 0x81"

As Milen accurately explains, Postgres interprets the statement as an octal number (\o201 == 0x81).

As Milen also describes, the E infront of the path doesn't help.

So a quick recap: Why is NpqSQL stopping my insertion of the \\2010?


Solution

  • Milen deserves credit for leading me to the answer - thanks!

    Appearantly NpgSQL performs one escape-iteration before inserting my SQL statement into Postgres. Thus to solve my problem, I replaced all the occurances of my backslashes with two backslashes instead:

    string path = ... my path ...
    path = path.Replace("\\", "\\\\");
    sqlStatement = "INSERT INTO images (file_location) VALUES ('" + path + "')";