user5813072 user5813072 - 3 months ago 10
C# Question

editing one column in the Csv File

i am trying to editing only one column within my csv. however the code does not seem to affect the file. the changes im trying to make is to change to separate the 4th column data with a comma.

class Program
{
static void Main(string[] args)
{
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "kaviaReport 02_08_2016.csv");
var fileContents = ReadFile(filePath);
foreach (var line in fileContents)
{
Console.WriteLine(line);
}

Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}

public static IList<string> ReadFile(string fileName)
{
var results = new List<string>();
int lineCounter = 0;
string currentLine = string.Empty;
var target = File
.ReadAllLines(fileName);
while ((currentLine = fileName) != null)//while there are lines to read
{
List<string> fielded = new List<string>(currentLine.Split(','));
if (lineCounter != 0)
{
//If it's not the first line
var lineElements = currentLine.Split(',');//split your fields into an array
var replace = target[4].Replace(' ', ',');//replace the space in position 4(field 5) of your array
results.Add(replace);
//target.WriteAllLines(string.Join(",", fielded));//write the line in the new file

}

lineCounter++;
File.WriteAllLines(fileName, target);


}

return results;
}
}

Bob Bob
Answer

while ((currentLine = fileName) != null) will set currentLine = fileName which will make the line always true and make a infinite loop

I would write it as a for loop instead of a while

public static IList<string> ReadFile(string fileName)
    {
        var target = File.ReadAllLines(fileName).ToList();
        // i = 1 (skip first line)
        for (int i = 1; i < target.Count; i++)
        {
           target[4] = target[4].Replace(' ', ','); //replace the space in position 4(field 5)
        }
        File.WriteAllLines(fileName, target);
        // Uncomment the RemoveAt(0) to remove first line
        // target.RemoveAt(0);
        return target;
    }
Comments