After following this topic I am able to create the new row but my question is how do I save or write the new line to the file?
I tried 'StreamWriter' but it only writes the newly created line.
Any suggestions please?
Here is my code so far:
string path = @"C:/CSV.txt";
string[] lines = File.ReadAllLines(path);
var splitlines = lines.Select(l => l.Split(','));
foreach (var line in splitlines)
{
if(line[1].Contains("34"))
{
line[1] = "100";
var newline = string.Join(",", line);
StreamWriter sr = new StreamWriter(path);
sr.WriteLine(newline);
sr.Close();
}
}
A CSV (Comma Separated Values) file is a special type of file that you can create or edit in Excel. Rather than storing information in columns, CSV files store information separated by commas.
To edit your csv files, we strongly advise you to use a simple text editor such as Notepad++ or Sublime Text. Using Excel to edit your files is more complex: Excel renders certain values such as ICCID or IMEI in numbers and truncates them, leading to information being not easily usable.
Here is your solution using StreamReader
class:
String path = @"C:\CSV.txt";
List<String> lines = new List<String>();
if (File.Exists(path));
{
using (StreamReader reader = new StreamReader(path))
{
String line;
while ((line = reader.ReadLine()) != null)
{
if (line.Contains(","))
{
String[] split = line.Split(',');
if (split[1].Contains("34"))
{
split[1] = "100";
line = String.Join(",", split);
}
}
lines.Add(line);
}
}
using (StreamWriter writer = new StreamWriter(path, false))
{
foreach (String line in lines)
writer.WriteLine(line);
}
}
If you want to overwrite the file, use this StreamWriter constructor with append = false
.
Maybe somthing like this, you probably will need to clean it up and add some error handling, but it does the job
string path = @"C:\\CSV.txt";
string[] lines = File.ReadAllLines(path);
for (int i = 0; i < lines.Length; i++)
{
string line = lines[i];
if (line.Contains(","))
{
var split = line.Split(',');
if (split[1].Contains("34"))
{
split[1] = "100";
line = string.Join(",", split);
}
}
}
File.WriteAllLines(@"C:\\CSV.txt", lines);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With