1

I have a csv file as shown below

enter image description here

I want to replace the text in the header. Aim is to replace _ underscores by a space.

Sample output

enter image description here

The Code I was trying was by using TextFieldParser

private void CSV_Operation(string path)
{
    using (TextFieldParser parser = new TextFieldParser(path))
    {
        // set the parser variables
        parser.TextFieldType = FieldType.Delimited;
        parser.SetDelimiters(",");

        bool firstLine = true;

        while (!parser.EndOfData)
        {
            string[] fields = parser.ReadFields();
            if (firstLine && fields != null)
            {
                //Code to replace this in actual .csv file, below code does not save these changes in the original file
                for (int i = 0; i < fields.Count(); i++)
                {
                    fields[i] = fields[i].Replace('_', ' ');
                }
            }

            // get the column headers
            if (firstLine)
            {
                firstLine = false;
            }
        }
    }
}

I want to persist the changes done to the header text in the original file. Any help?

2
  • I've removed the [asp.net] and [console-application] tags from your question because it's not clear how they relate to your specific question. If they are relevant, please edit your question to saw how. Commented Sep 7, 2020 at 12:40
  • 1
    Your first problem is using TextFieldParser in an ASP application. TextFieldParser is from the VisualBasic assembly, which you should avoid using. Commented Sep 7, 2020 at 12:40

3 Answers 3

2

If you want to change columns' heads (i.e. 1st line) only, while keeping csv body intact you can try

using System.IO;
using System.Linq;

...

private void CSV_Operation(string path) {
  var file = File
    .ReadLines(path)
    .SkipWhile(line => string.IsNullOrWhiteSpace(line)) // To be on the safe side
    .Select((line, index) => index == 0 // do we have header? 
       ? line.Replace('_', ' ') // replace '_' with ' '
       : line)                  // keep lines as they are 
    .ToList();                  // Materialization, since we write into the same file

  File.WriteAllLines(path, file);
}
Sign up to request clarification or add additional context in comments.

Comments

0

A quick alternative could be:

private void CSV_Operation(string path)
{
   File.WriteAllLines(path,  
                      File.ReadAllText(path).Replace('_', ' '),       
                      Encoding.UTF8);
}

2 Comments

ReadAllText instead of ReadAllLines?
But this will change all underscores, not just the header
0

You could do something like this

//read all the lines but skip the first
var lines = File.ReadLines(Server.MapPath("/test.csv")).Skip(1).ToList();

//create a new header if you want more than just remove the _
string newHeader = "ID;Name;Address;Contact";

//merge both
string newCsv = string.Format("{0}\r\n{1}", newHeader, string.Join("\r\n", lines));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.