Escape a string (add slashes) in VB.net?

escaping, string, vb.net

Solution

What exactly do you mean by escaping? VB.NET doesn't have 'escaping' in the same way that c-style languages do.

Now, if you want to ensure that there are no single-qoutes in the pClientId variable, then you have two options:

Option 1 (not recommended for this scenario): do a simple replace. I.e.

pClientId = String.Replace(pClientId, "'","''")

But, as noted, I would NOT do this for what appears to be a SQL Command. What I would do is Option 2: use data parameters to pass parameters to your DB during sql commands

For example:

Dim cn As New SqlConnection(connectionString)
Dim cmd As New SqlCommand
cn.Open
cmd.Connection=cn
cmd.CommandType=CommandType.StoredProcedure
cmd.CommandText= "sp_Message_insert"
cmd.Parameters.add(New SqlParameter("@clientid", pClientId)
cmd.Parameters.add(New SqlParameter("@message", pMessage)
cmd.Parameters.add(New SqlParameter("@takenby", pUserId)
cmd.Parameters.add(New SqlParameter("@recipients", pRecipients)
cmd.ExecuteNonQuery

Problem

Very simple question (surprisingly I can't find a similar question anywhere): how do I escape form data in VB.net? I have various lines like this: ``` Dim query As String = "exec sp_Message_insert @clientid='" + pClientId + "', @message='" + pMessage + "', @takenby='" + pUserId + "', @recipients='" + pRecipients + "'" ``` If I use an apostrophe in the message then of course this screws up the query. I've looked through the intellisense functions on the string but don't see anything appropriate...

Original source