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
ReadLinesso you can't write back to it, you haven't opened it with ReadWrite access.var lines = File.ReadAllLines(path);(notice theAll) closes the file handle after reading. You could try using that for files that are not unusually big (<100MB? If it get's bigger than that you should work with a DB anyways).