Reputation: 115
Im trying to use Stringbuilder to build me a csv file and some of the fields from the files I'm using have double quotes in.
I have this code as you can see I am trying to use the .replace to remove the "
and replace with nothing
, this throws an empty char literal error. Is there an easier way of removing all double quotes `
public void Manipulatefile(string csv, string suffix)
{
StringBuilder formattedData = new StringBuilder();
// Read all file lines into a string array.
string path = @csv;
string[] fileLines = File.ReadAllLines(path);
foreach (string fileLine in fileLines)
{
string[] lineItems = fileLine.Split(new char[1] { ',' });
string forename = lineItems[0];
string surname = lineItems[1];
formattedData.Append(forename);
// Add the CSV seperator.
formattedData.Append(",");
// Append the forename to the current CSV output line.
formattedData.Append(surname);
formattedData.Append(",");
formattedData.Append(forename.Substring(1,1));
formattedData.Append(surname);
formattedData.Append(suffix);
formattedData.Replace('"', '');
formattedData.AppendLine();
File.WriteAllText(@"C:\test\MyFile.csv", formattedData.ToString());
}
Thanks
Upvotes: 0
Views: 2783
Reputation: 460058
There's no such thing as an empty char. The closest you can get is '\0'
, the Unicode "null" character.
But why don't you use a string
? You need to escape "
with \
:
formattedData.Replace("\"", "");
Upvotes: 1
Reputation: 9645
.Replace can accept a string, and an empty string is valid, so just escape the double quotes
formattedData.Replace("\"", "");
It's worth bearing in mind that your line of code that splits by comma
string[] lineItems = fileLine.Split(new char[1] { ',' });
will have the undesired effect of splitting any string with a comma in it. The whole point of double quotes is to isolate a comma so that column can contain comma. For example
name,address,phone
"Joe","22 acacia avenue, mean street, LA","555-1234"
Your code will split this line into five values, not three as expected. You should really use a dedicated CSV parser instead.
Upvotes: 3
Reputation: 203821
A character literal needs to be exactly one character. A string
is a sequence of zero or more characters. You want a string that has no characters, since you can't have a character that represents no character.
There is another overload of Replace
that accepts strings, rather than characters, for its parameters.
On a side note, CSV files can escape quotes inside of the field value with another quote, so if your field value is: This is my "Value"
you can write it as This is my ""Value""
and it will be interpreted properly. If you're fine removing the quotes entirely in your situation that's fine, just know that there is a defined case for how to actually keep the quotes in without violating the syntax.
Upvotes: 3