I'm developing a password storage application where a user has to enter a file name, choose a file extension from a combobox and then type their file content in the provided textbox. The filename and extension is only for if they choose to export it. Most of the data I'm inserting into the database is working fine and inserting/able to retrieve from SQL Server database without an issue. but as soon as my file content has characters such as ""/ '/ ()/ etc it gives me the error
System.Data.SqlClient.SqlException: 'Incorrect syntax near 't'. Unclosed quotation mark after the character string ')'.'
How can I make it possible for the file content string to be inserted into database exactly as entered into textbox: here's the code for the insert after clicking savefile button where I get the initial error:
private void btnSaveFile_Click(object sender, EventArgs e)
{
string extensionType = comboExtension.GetItemText(comboExtension.SelectedItem);
if (txtFileName.Text == "")
{
MessageBox.Show("Please Enter A Valid File Name", "Please Fill In", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else if (!txtFileName.Text.All(char.IsLetterOrDigit))
{
MessageBox.Show("File Name can only contain letters or numbers, No Special Characters", "Incorrect Input", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtFileName.Clear();
}
else if (extensionType == "")
{
MessageBox.Show("Please Select An Extension Type", "Select File Type", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else if (txtDescription.Text.Length > 7999)
{
MessageBox.Show("File content cannot exceed 8000 characters", "Characters Exceeded", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else {
string fname = txtFileName.Text;
string content = txtDescription.Text;
string forUser = Form1.userId;
string dateAdded = DateTime.Now.ToString();
connection.Open();
cmd = new SqlCommand("insert into [Files] values('" + fname + "', '" + extensionType + "', '" + content + "', '" + dateAdded + "', '" + forUser + "')", connection);
cmd.ExecuteNonQuery();
connection.Close();
this.Alert("File Created Successfully");
this.Alert("File Created Successfully");
txtFileName.Clear();
txtDescription.Clear();
comboExtension.Text = ("File Extension");
}
}