0

So I'm working on making a submit content page that will store the users input into a database, here is the code I have so far:

protected void submitData_Click(object sender, EventArgs e)
    {
        string userId = HttpContext.Current.User.Identity.Name;
        int categoryId = Convert.ToInt32(categories.SelectedValue);
        if (categoryId > 0 && content.Text != "" && description.Text != "")
        {
            using (SqlConnection connection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="C: \Users\Will\Documents\Visual Studio 2015\WebSites\inshort\App_Data\ASPNETDB.MDF";Integrated Security=True"))
            {
                SqlCommand cmd = new SqlCommand("INSERT INTO aspnet_newscontent (author, username, date, category, content, description) VALUES (@author, @username, @date, @category, @content, @description)");
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.Connection = connection;
                cmd.Parameters.AddWithValue("@author", nameInput.Text);
                cmd.Parameters.AddWithValue("@username", userId);
                cmd.Parameters.AddWithValue("@date", DateTime.Today);
                cmd.Parameters.AddWithValue("@category", categoryId);
                cmd.Parameters.AddWithValue("@content", content.Text);
                cmd.Parameters.AddWithValue("@description", description.Text);
                connection.Open();
                cmd.ExecuteNonQuery();
            }
        }
        else
        {
            errorLabel.Text = "Please fill in the required fields.";
        }
    }

However, I am getting an error saying that the connection string contains an invalid character "\", which makes sense but whenever I go to my database's properties and look at the Connection String property, that is what it says.
I am using Microsoft Sql Server Express to have the database locally hosted if that changes anything. Anyone know how to format these connection strings?

Will Fisher
  • 413
  • 5
  • 18
  • Escape the double quotes in the string, for verbatim string, use double *double* quotes like `@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=""C: \Users\Will\Documents\Visual Studio 2015\WebSites\inshort\App_Data\ASPNETDB.MDF"";Integrated Security=True"` -- VOTING TO CLOSE AS A TYPO – Habib Jul 06 '15 at 17:42
  • Well it is possible that this post would help people with similar problems learn how to properly use escape characters. – Will Fisher Jul 06 '15 at 17:46
  • There are plenty of posts on SO for that as well, this question could be considered a duplicate of http://stackoverflow.com/questions/1928909/can-i-escape-a-double-quote-in-a-verbatim-string-literal – Habib Jul 06 '15 at 18:02

3 Answers3

2

You must escape certain characters in a C# string. If you take away the "literal" string character (@), it will look like this:

using (SqlConnection connection = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\\Will\\Documents\\Visual Studio 2015\\WebSites\\inshort\\App_Data\\ASPNETDB.MDF\";Integrated Security=True"))
oppassum
  • 1,746
  • 13
  • 22
2

Look at the syntax highlighting. You're trying to put un-escaped double-quotes in a string, which clearly confuses the parser because it thinks your string is terminating earlier and just full of syntax errors after it.

To escape quotes in a verbatim string literal (one prepended with an @), you need to "double"-double quote them. Like this:

@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=""C:\Users\Will\Documents\Visual Studio 2015\WebSites\inshort\App_Data\ASPNETDB.MDF"";Integrated Security=True"
David
  • 208,112
  • 36
  • 198
  • 279
  • This did the trick, I will accept this answer as soon as it lets me. – Will Fisher Jul 06 '15 at 17:45
  • You really should use this format: Data Source=DataBaseServerName;Initial Catalog=SQLDatabaseName – Chuck Jul 06 '15 at 17:49
  • @Chuck: Would that work with LocalDB at all? Changing the entire SQL infrastructure just to make the connection string look cleaner doesn't seem like a good use of effort. – David Jul 06 '15 at 17:57
1

As others have pointed out, you need to escape the special characters in your connection string.

In practice, with asp.net many developers simply place the connection string in their web.config and then access it later this way if it ever changes you only have to change it in one place:

  <connectionStrings>
    <add name="MyConnection" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C: \Users\Will\Documents\Visual Studio 2015\WebSites\inshort\App_Data\ASPNETDB.MDF;Integrated Security=True/>
  </connectionStrings>

And then access it using:

private string GetConnectionString()
{
    return System.Configuration.ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
}
amza
  • 780
  • 2
  • 7
  • 32