Within my CSV file I have a column which holds a string and a date time type. Which is the 5th column in my CSV file which has this data (TUI 01/01/01). I applied some changes in order to a comma on the space to separate this value in two different columns(TUI,01/01/01). However, these changes affect other column data which have a space between their values. I would just like to apply these changes only to affect the fifth column.
Any suggestion would be much appreciating.
static void Main(string[] args)
{
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "InventoryReport 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>();
var target = File
.ReadAllLines(fileName)
.Skip(1) // Skip the line with column names
.Select(line => line.Replace(' ', ',')); // ... splitting pattern
// Writing back to some other file
File.WriteAllLines(fileName, target);
return results;
}
}
ok you are clearly applying that replace to whole file that's why it's affecting all the columns, try another way :
-loop each line
-in each loop split elements using commas
var lineElements = line.split(',');
-and then specifically apply that to 5th column :
var fifthElement = lineElements[4].Replace(' ', ',');
-that will apply the effect only on 5th element
-combine it up and get whole line as you were
Your current way is affecting the whole line( .Select(line => line.Replace(' ', ','))
), not just the 5th field on the line. Here's another way.
Option 1
public Form1()
{
InitializeComponent();
ReWriteFile(@"M:\StackOverflowQuestionsAndAnswers\38873875\38873875\testdata.csv");//call the method
}
public void ReWriteFile(string fileName)
{
using (StreamWriter sw = new StreamWriter(@"M:\StackOverflowQuestionsAndAnswers\38873875\38873875\testdata_new.csv"))
{
string currentLine = string.Empty;
using (StreamReader sr = new StreamReader(fileName))//
{
while ((currentLine = sr.ReadLine()) != null)//while there are lines to read
{
string[] fielded = currentLine.Split(',');//split your fields into an array
fielded[4] = fielded[4].Replace(" ", ",");//replace the space in position 4(field 5) of your array
sw.WriteLine(string.Join(",", fielded));//write the line in the new file
}
}
}
}
My starting data was this( there is a mismatch in column counts, but it does not keep anything from working as it should for the purpose of this question ):
col1,col2,col3,col4,col5,col6
col 1 data,col 2 data,col 3 data,col 4 data,TUI 01/01/01,col 5 data,col 6 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI 01/01/01,col 5 data,col 6 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI 01/01/01,col 5 data,col 6 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI 01/01/01,col 5 data,col 6 data
It became this after it went through the method:
col1,col2,col3,col4,col5,col6
col 1 data,col 2 data,col 3 data,col 4 data,TUI,01/01/01,col 5 data,col 6 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI,01/01/01,col 5 data,col 6 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI,01/01/01,col 5 data,col 6 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI,01/01/01,col 5 data,col 6 data
After reading your question here how to display the column names on my csv file I realized you must be skipping the first row for a good reason so I updated my code to do so and to fix your question's problem at the same time.
This option writes the header record as-is
/// <summary>
/// In this method I use the lineCounter as my position tracker to know which line I'm readin at the time
/// </summary>
/// <param name="fileName"></param>
public void ReWriteFileDontAffectFirstRow(string fileName)
{
int lineCounter = 0;//lets make our own position tracker
using (StreamWriter sw = new StreamWriter(@"M:\StackOverflowQuestionsAndAnswers\38873875\38873875\testdata_new2.csv"))
{
string currentLine = string.Empty;
using (StreamReader sr = new StreamReader(fileName))
{
while ((currentLine = sr.ReadLine()) != null)//while there are lines to read
{
if (lineCounter != 0)
{
//If it's not the first line
string[] fielded = currentLine.Split(',');//split your fields into an array
fielded[4] = fielded[4].Replace(" ", ",");//replace the space in position 4(field 5) of your array
sw.WriteLine(string.Join(",", fielded));//write the line in the new file
}
else
{
//If it's the first line
sw.WriteLine(currentLine);//Write the line as-is
}
lineCounter++;
}
}
}
}
Original data was this( there is a mismatch in column counts, but it does not keep anything from working as it should for the purpose of this question )
col 1,col 2,col 3,col 4,col 5,col 6
col 1 data,col 2 data,col 3 data,col 4 data,TUI 01/01/01,col 5 data,col 6 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI 01/01/01,col 5 data,col 6 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI 01/01/01,col 5 data,col 6 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI 01/01/01,col 5 data,col 6 data
Data after going through the method
col 1,col 2,col 3,col 4,col 5,col 6
col 1 data,col 2 data,col 3 data,col 4 data,TUI,01/01/01,col 5 data,col 6 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI,01/01/01,col 5 data,col 6 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI,01/01/01,col 5 data,col 6 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI,01/01/01,col 5 data,col 6 data
This option adds a field to the header record
public void ReWriteFileAdjustHeaderRecordToo(string fileName)
{
int lineCounter = 0;//lets make our own position tracker
using (StreamWriter sw = new StreamWriter(@"M:\StackOverflowQuestionsAndAnswers\38873875\38873875\testdata_new3.csv"))
{
string currentLine = string.Empty;
using (StreamReader sr = new StreamReader(fileName))
{
while ((currentLine = sr.ReadLine()) != null)//while there are lines to read
{
List<string> fielded = new List<string>(currentLine.Split(','));//splits your fields into a list of fields. This is no longer a string[]. Its a list so we can "inject" the new column in the header record.
if (lineCounter != 0)
{
//If it's not the first line
fielded[4] = fielded[4].Replace(" ", ",");//replace the space in position 4(field 5) of your array
sw.WriteLine(string.Join(",", fielded));//write the line in the new file
}
else
{
//If it's the first line
fielded.Insert(4, "new inserted col");//inject the new column into the list
sw.WriteLine(string.Join(",", fielded));//write the line in the new file
}
lineCounter++;
}
}
}
}
Starting data( this data has the right starting column count )
col 1,col 2,col 3,col 4,col 5,col 6
col 1 data,col 2 data,col 3 data,col 4 data,TUI 01/01/01,col 5 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI 01/01/01,col 5 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI 01/01/01,col 5 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI 01/01/01,col 5 data
Data after the method
col 1,col 2,col 3,col 4,new inserted col,col 5,col 6
col 1 data,col 2 data,col 3 data,col 4 data,TUI,01/01/01,col 5 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI,01/01/01,col 5 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI,01/01/01,col 5 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI,01/01/01,col 5 data
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.