Edit and/or Delete a row on CSV file - c#

I have a CSV file. I need to write a code that we can get a row from CSV by username. And I need to either update or delete that row from the CSV file. I was managed to get the row data by username. But I haven't got any idea how to write the code for Update or delete function. My code to get single row as follows
StreamReader reader = new StreamReader(System.IO.File.OpenRead(#"C:\Test\test.CSV"));
UserDetailsViewModel objInput = new UserDetailsViewModel();
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
if (!String.IsNullOrWhiteSpace(line))
{
string[] values = line.Split(',');
if (values[0] == "Bharat")
{
objInput.FirstName = values[0];
objInput.LastName = values[1];
objInput.Address1 = values[2];
objInput.Address2 = values[3];
objInput.City = values[4];
objInput.State = values[5];
objInput.ZipCode = values[6];
break;
}
}
}
reader.Dispose();
return View(objInput);
Please someone help me to write a code for Update and delete on CSV file.
Thanks in Advance.

You can achieve your desired result, using below approach.
-> First you have to read your .csv file.
-> Then iterate through every line of file, meanwhile you can choose any row for edit/delete then make change to that row and store that row into string list.
-> At last you have to write string list to file. that's all.
For Example:
List<String> lines = new List<String>();
using (StreamReader reader = new StreamReader(System.IO.File.OpenRead(#"C:\Test\test.CSV"));)
{
String line;
while ((line = reader.ReadLine()) != null)
{
if (line.Contains(","))
{
String[] split = line.Split(',');
if (//condition for Edit record like : split[1] == "abc" etc.)
{
// update that
split[1] = "xyz";
line = String.Join(",", split);
lines.Add(line);
}
if (//condition for Delete row.)
{
// don't add that row into string list
}
}
}
}
using (StreamWriter writer = new StreamWriter(#"C:\Test\test.CSV", false))
{
foreach (String line in lines)
writer.WriteLine(line);
}

Reading and wirting csv is typically trickier than it seems to be at first glance.
Use a library like KBCsv (https://github.com/kentcb/KBCsv) for that task

Related

C# excel color text

I'm currently using the below code to compare two csv files with each other. I can select a column in the file and it will compare the rows in that column, it then writes the incorrect and correct rows into another csv file. But now I want to change the color the text 'this row is not the same' so that it's more noticeable. How can I do this?
public void comparing(int selectedRow, string filenaname, string filename2)
{
List<string> lines = new List<string>();
List<string> lines2 = new List<string>();
try
{
StreamReader reader = new StreamReader(System.IO.File.OpenRead(filename));
StreamReader read = new StreamReader(System.IO.File.OpenRead(filename2));
List<string> lijnen = new List<string>();
string line;
string line2;
string differencesFile= #"C:\Users\Mylan\Desktop\differences.csv";
while ((line = reader.ReadLine()) != null && (line2 = read.ReadLine()) != null)
{
string[] split = line.Split(Convert.ToChar(csvSeperator));
string[] split2 = line2.Split(Convert.ToChar(csvSeperator));
if (split[selectedRow] != split2[selectedRow])
{
lijnen.Add("This row is not the same:, " + line);
}
else if(test == test2)
{
System.Windows.Forms.MessageBox.Show("The whole file is the same");
break;
}
else
{
lines.Add("This row is the same:, " + line);
}
}
System.IO.File.WriteAllLines(differencesFile, lines);
System.Diagnostics.Process.Start(differencesFile);
reader.Dispose();
read.Dispose();
}
catch
{
}
}
}
}
I think it's impossible to do what you want with CSV files. Excel reads only the values and separate these in columns, that's all.
If you want to create an Excel file directly by code, you need to use for example the Open XML :
https://msdn.microsoft.com/en-gb/library/office/bb448854.aspx
This is what I use to create, edit Excel files (and Powerpoint files too). It's a bit tricky at beginning but it's a solution...

Replace data/value of csv file

I want to count the number of some strings and store it into a csv file. I've tried it but I don't know if this is the correct way and in addition, there are two problems.
First of all, here is my method:
public void CountMacNames(String macName)
{
string path = #"D:\Counter\macNameCounter.csv";
if (!File.Exists(path))
{
File.Create(path).Close();
}
var lines = File.ReadLines(path);
foreach (var line in lines)
{
bool isExists = line.Split(',').Any(x => x == macName);
if (isExists)
{
// macName exists, increment it's value by 1
}
else
{
// macName does not exists, add macName to CSV file and start counter by 1
var csv = new StringBuilder();
var newLine = string.Format("{0},{1}", macName, 1);
csv.AppendLine(newLine);
File.WriteAllText(path, csv.ToString());
}
}
}
The first problem is this IOException:
The process cannot access the file 'D:\Counter\macNameCounter.csv'
because it is being used by another process.
The second problem is, that I don't know how to increment the value by one, if a macName exists in the csv file (see first comment)
EDIT: Example for method "CountMacNames" call:
CountMacNames("Cansas");
CountMacNames("Wellback");
CountMacNames("Newton");
CountMacNames("Cansas");
CountMacNames("Princet");
Then, the CSV file should contain:
Cansas, 2
Wellback, 1
Newton, 1
Princet, 1
OK, this is what I'd do:
public void CountMacNames(String macName)
{
string path = #"D:\Counter\macNameCounter.csv";
// Read all lines, but only if file exists
string[] lines = new string[0];
if (File.Exists(path))
lines = File.ReadAllLines(path);
// This is the new CSV file
StringBuilder newLines = new StringBuilder();
bool macAdded = false;
foreach (var line in lines)
{
string[] parts = line.Split(',');
if (parts.Length == 2 && parts[0].Equals(macName))
{
int newCounter = Convert.ToIn32(parts[1])++;
newLines.AppendLine(String.Format("{0},{1}", macName, newCounter));
macAdded = true;
}
else
{
newLines.AppendLine(line.Trim());
}
}
if (!macAdded)
{
newLines.AppendLine(String.Format("{0},{1}", macName, 1));
}
File.WriteAllText(path, newLines.ToString());
}
This code does this:
Read all the lines from file only if it exists - otherwise we start a new file
Iterate over all the lines
If the first part of a 2-part line equals the mac, add 1 to counter and add line to output
If the first part doesn't match or the line format is wrong, add the line to output as is
If we didn't find the mac in any line, add a new line for the mac with counter 1
Write the file back
You can't read and write to the same file at the same time (in a simple way).
For small files, there are already answers.
If your file is really large (too big to fit in memory) you need another approach:
Read input file line by line
optinally modify the current line
write line to a temporary file
If finished delete input file, rename temporary file
For the first problem you can either read all the lines into memory and work there then write it all out again, or use streams.
using (FileStream fs = File.Open(filePath, FileMode.Create, FileAccess.ReadWrite))
{
var sw = new StreamWriter(fs);
var sr = new StreamReader(fs);
while(!streamReader.EndOfStream)
{
var line = sr.ReadLine();
//Do stuff with line.
//...
if (macExists)
{
//Increment the number, Note that in here we can only replace characters,
//We can't insert extra characters unless we rewrite the rest of the file
//Probably more hassle than it's worth but
//You could have a fixed number of characters like 000001 or 1
//Read the number as a string,
//Int.Parse to get the number
//Increment it
//work out the number of bytes in the line.
//get the stream position
//seek back to the beginning of the line
//Overwrite the whole line with the same number of bytes.
}
else
{
//Append a line, also harder to do with streams like this.
//Store the current position,
//Seek to the end of the file,
//WriteLine
//Seek back again.
}
}
}
You need to read the file in and release it, like this, to avoid the IO exception:
string[] lines = null;
using (var sr = new System.IO.StreamReader(path))
lines = sr.ReadToEnd().Split(new string[] {"\r", "\n"}, StringSplitOptions.RemoveEmptyEntries);
As for the count, you can just add an int value, change the method return type as int, too.
public int CountMacNames(String macName, String path)
{
if (!File.Exists(path))
{
File.Create(path).Close();
}
string[] lines = null;
using (var sr = new System.IO.StreamReader(path))
lines = sr.ReadToEnd().Split(new string[] {"\r", "\n"}, StringSplitOptions.RemoveEmptyEntries);
return lines.Where(p => p.Split(',').Contains(macName)).Count();
}
and inside the method that calls it:
var path = #"<PATH TO FILE>";
var cnt = CountMacNames("Canvas", path);
if (cnt > 0)
{
using (var sw = new StreamWriter(path, true, Encoding.Unicode))
sw.WriteLine(string.Format("Canvas,{0}", cnt));
}
Now, var res = CountMacNames("Canvas","PATH"); will return 2, and the lines "Canvas,2" or "Newton,1" will be appended to the file, without overwriting it.

Delete last line of file, when using the data to draw a chart c#

I am in a trouble, when I am trying to delete the last line of my csv file, when I'm trying to draw a chart of the data.
My file contains a lot of data, which I get through the following code:
public void StreamOpen()
{
Stream stream;
OpenFileDialog getDialog = new OpenFileDialog();
getDialog.Filter = "csv File|*.csv";
getDialog.Title = "Get a .csv file";
if (getDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if ((stream = getDialog.OpenFile()) != null)
{
strFileName = getDialog.FileName;
string[] filetext = File.ReadAllLines(strFileName);
}
stream.Flush();
}
}
public void OpenFile()
{
if (!File.Exists(strFileName))
{
ListA();
ListB();
}
if (strFileName != null)
{
var reader = new StreamReader(File.OpenRead(strFileName));
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(';');
UpdateChart();
listA.Add(values[0]);
listB.Add(values[1]);
}
}
ListA();
ListB();
}
The problem is, that in the last line of my file, I save a text like
"Count of movements" + value
, and this value I want to skip when drawing that chart, instead I want to show that value in a textbox.
Now a error occur, that listA and listB is not the same, and I see why, because that last line is taken as a part of listA.
Hope you can help me to delete that last line, and help me to show how to save that value in a textbox.
Output in textfile:
09:03:28 ; 0
09:03:29 ; 1
09:03:30 ; 0
09:03:31 ; 0
Count of movements 2
Change your code to this
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (line.StartsWith("Count"))
break;
/....
}
Skip if last line starts with certain string
What about this approach:
string[] values = line.Split(';');
if(values.Length != expected_column_count) // then ignore
Edit
Or if something other is special about the unwanted line, for example it always starts with the same text:
if(line.StartsWith(unwanted_prefix)) // then ignore

Extract data from text file

I need to extract some data from a text file and insert to columns in excel sheet. I know how to do this if the rows and the length of the string is known.
try
{
using (System.IO.StreamReader sr = new System.IO.StreamReader("test.txt")
{
string line;
while ((line = sr.ReadLine()) != null)
{
listSNR.Items.Add(line.Substring (78,4));
}
}
}
But the particular text file is complex and the starting index or the length cannot be provided. But the starting word (PCPU01) of the row is known.
Eg: PCPU01,T2716,0.00,0.01,0.00,0.00
output:
T2716 0 0.01 0 0
In that case can somebody please let me know how to extract the texts?
using(System.IO.StreamReader sr = new System.IO.StreamReader("test.txt"))
{
string line;
while((line = sr.ReadLine()) != null)
{
string[] split = line.Split(',');
//...
}
}
split[0] will return "PCPU01", split[1] "T2716" and so on.
You can split one string into an array of strings, separated by a given character. This way, you could split the source string by a comma and use the resulting strings to build your output. Example:
string source = "PCPU01,T2716,0.00,0.01,0.00,0.00";
string[] parts = source.Split(',');
StringBuilder result = new StringBuilder();
result.Append(parts[1]); // The second element in the array, i.e. T2716
result.Append(" ");
result.Append(parts[2]); // 0.00
... // And so on...
return result.ToString() // return a string, not a StringBuilder
I hope this helps a little bit. You might have to tweak it to your needs. But this is a higher level code that gives you general idea of extracting data off a notepad.
DialogResult result = openFileDialog.ShowDialog();
Collection<Info> _infoCollection = new Collection<Info>();
Collection<string> listOfSubDomains = new Collection<string>();
string[] row;
string line;
// READ THE FILE AND STORE IT IN INFO OBJECT AND STORE TAHT INFO OBJECT IN COLLECTION
try
{
using (StreamReader reader = new StreamReader(openFileDialog.FileName))
{
while((line = reader.ReadLine()) != null)
{
Info _info = new Info();
row = line.Split(' ');
_info.FirstName = row[0];
_info.LastName = row[1];
_info.Email = row[2];
_info.Id = Convert.ToInt32(row[3]);
_infoCollection.Add(_info);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
thanks for the answers. What i wanted is to identify the particular line in the text file and split the line into columns. So i was able to do this by calling a GetLine method:
string line15=GetLine(#"test.txt",15);
public string GetLine(string fileName, int line)
{
using (System.IO.StreamReader ssr = new System.IO.StreamReader("test.txt"))
//using (var ssr = new StreamReader("test.txt"))
{
for (int i = 1; i < line; i++)
ssr.ReadLine();
return ssr.ReadLine();
}
}
Then i splitted this line by using the delimiter (,)
This was my approach in C#. It takes a string input (which you can get out of a text file) and an int with which line you want to get. It then separates the string at a given seperator char to a list which in turn is then read out. If the given line number is lower than the count of the created list, the entry is given back.
public string GetLine(string multiline,int line)
{
List<string> lines = new List<string>();
lines = multiline.Split('\n').ToList<string>();
return lines.Count >= line ? lines[line] : "";
}

How to use textfieldParser to edit a CSV file?

I wrote a small function that reads a csv file using textField line by line , edit it a specific field then write it back to a CSV file.
Here is the code :
private void button2_Click(object sender, EventArgs e)
{
String path = #"C:\file.csv";
String dpath = #"C:\file_processed.csv";
List<String> lines = new List<String>();
if (File.Exists(path))
{
using (TextFieldParser parser = new TextFieldParser(path))
{
String line;
parser.HasFieldsEnclosedInQuotes = true;
parser.Delimiters = new string[] { "," };
while ((line = parser.ReadLine()) != null)
{
string[] parts = parser.ReadFields();
if (parts == null)
{
break;
}
if ((parts[12] != "") && (parts[12] != "0"))
{
parts[12] = parts[12].Substring(0, 3);
//MessageBox.Show(parts[12]);
}
lines.Add(line);
}
}
using (StreamWriter writer = new StreamWriter(dpath, false))
{
foreach (String line in lines)
writer.WriteLine(line);
}
MessageBox.Show("CSV file successfully processed ! ");
}
}
The field I want to edit is the 12th one (parts[12]):
for example : if parts[12] = 000,000,234 then change to 000
the file is created the problem is it does not edit the file and half the records are missing. I am hoping someone could point the mistake.
You call both parser.ReadFields() and parser.ReadLine(). Each of them advance the cursor by one. That's why you're missing half the rows. Change the while to:
while(!parser.EndOfData)
Then add parts = parser.ReadFields(); to the end of the loop. Not having this is why you're edit isn't being seen.
You can also remove:
if (parts == null)
{
break;
}
Since you no longer have line, you'll need to use the fields to keep track of your results:
lines.Add(string.Join(",", parts));//handle string escaping fields if needed.

Categories

Resources