Search code examples
c#stringbuildercharacter-replacement

C# Stringbuilder replace with a null value


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


Solution

  • .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.