I'm facing a problem with my code in C# where I'm writing to csv file (saving input data from textboxes).On the same time I want to add row number to each new row saved. I wrote this code but the error is showing: Sysytem.IO.IOException 'The process cannot acess the file because it's used by another process'. I made sure I'm closing the streamwriter and streamreader. I don't know how else I can improve my code.
var filePath = "csvFile.csv";
using (StreamWriter sw = new StreamWriter(new FileStream(filePath, FileMode.Create, FileAccess.Write)))
try
{
//Count rows in csv file and add new row number
string file = new StreamReader("csvFile.csv").ReadToEnd();
string[] lines = file.Split('\n');
int countOfLines = lines.GetLength(0);
sw.WriteLine("{0},{1},{2},{3},{4},{5}"
, countOfLines + 1
, txtEventName.Text
, txtEventType.Text
, txtAttributeName.Text
, txtAValue.Text
, txtEventDescrip.Text);
// Ensure data is written to disk
sw.Close();
}
catch()
{
}