Clinton Portis
Clinton Portis

Reputation: 11

Pass user input (parameters) in the query string (SqlCommand.CommandText), without getting a VS code analysis warning

I think the main point of my question is: what is best practise or is Visual Studio 2019 giving me wrong hints about reviewing the query string?

I have checked this example from Microsoft where the warning-code is sent me, but the following warning keeps popping up. The example gives obsolete code so I might look in the wrong place..

Review if the query string passed to 'string SqlCommand.CommandText' in 'GetTrumpfCadCamDocuments', accepts any user input.

The code was different, but when I do it the way the docs suggest the code looks like this:


/// The sqlfilepath is a content file which looks like this:
/// SELECT * FROM [R_DOCUMENT] WHERE [TYPE] = @type
/// Writing out the file content as a string is also used sometimes
/// which gives the same error.

string query = File.ReadAllText(sqlfilepath);

using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();

    using (SqlCommand command = new SqlCommand())
    {
        command.Connection = connection;
        command.Parameters.AddWithValue("@type", type);
        command.CommandText = query; //warning gets triggered here
        
        .....
    }
}

Upvotes: 1

Views: 386

Answers (0)

Related Questions