Home > database >  How to write comma to .csv files C#
How to write comma to .csv files C#

Time:12-06

I have the following query -

string query = "Insert into table(userId,companyID) values("   userId   ","   SplitedLine[1]   ")";
writer.WriteLine(query);

When I am printing running this code then it is not printing the entire query in one column, rather it is breaking the query wherever there is a comma.

I tried this

How to write a value which contain comma to a CSV file in c#?

string query = "Insert into table(userId"  "\",\"" "companyID) values ("   userId   "\",\""   SplitedLine[1]   ")";
writer.WriteLine(query);

But this is printing my insert commands in wrong format. Please help.

CodePudding user response:

I think the title of your question is ambiguous. You wanted to soround the values by quotation marks ("). But you made a mistake by escaping the " in the table part, it seams escaped " and not escaped was misked up.

Try to go with

string query = $"Insert into table(\"{userId}\",\"{companyID}\") values(\"{ userId}\",\"{SplitedLine[1]}\")";

CodePudding user response:

You could consider converting the string into another form and then converting it back e.g.

var bytes = Encoding.UTF8.GetBytes(query);
var stringToStore = Convert.ToHexString(bytes);

this can be included with the rest of your comma delimited text.

The on reading back:

var bytes = Convert.FromHexString(columnText);
var query = Encoding.UTF8.GetString(bytes);

Where columnText is the data that you had previously stored on the column that holds the query.

  • Related