Booney440 Booney440 - 9 months ago 40
C# Question

c# How to release a file after read streamwriter / reader

I have a winform using CsvHelper I can read and write fine. I have several files as I open and reopen them I will get an error after a few times "The process cannot access the file 'D:.csv' because it is being used by another process".
Cant figure out how to fix it. they need to be closed after used but dont know how.Can anyone help?

thanks

private void btnRead_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "CSV|*.csv", ValidateNames = true })
{
if (ofd.ShowDialog() == DialogResult.OK)
{

var sr = new StreamReader(new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read, FileShare.None));
var csv = new CsvReader(sr);
lunchBindingSource.DataSource = csv.GetRecords<Lunch>().ToString();
lunchBindingSource.DataSource = csv.GetRecords<Lunch>();


{
}
}
}
}

Answer Source

Take a look at the using statement. It will automatically handle closing the stream.