0

I'm trying to allow the user to add another entry to the CSV file my program is building. It is building it out of a database like this:

public void CreateCsvFile()
    {
        var filepath = @"F:\A2 Computing\C# Programming Project\ScheduleFile.csv";
        var ListGather = new PaceCalculator();

        var records =
            from record in ListGather.NameGain()
                .Zip(ListGather.PaceGain(),
                    (a, b) => new { Name = a, Pace = b })
            group record.Pace by record.Name into grs
            select String.Format("{0},{1}", grs.Key, grs.Average()); //reduces the list of integers down to a single double value by computing the average.

        File.WriteAllLines(filepath, records);
    }

I then am calling it into a datagridview like this:

 private void button2_Click(object sender, EventArgs e)
    {
        CreateExtFile CsvCreate = new CreateExtFile();
        CsvCreate.CreateCsvFile();
        return;
    }

private void LoadAthletes()
    {
        string delimiter = ",";
        string tableName = "Schedule Table";
        string fileName = @"F:\A2 Computing\C# Programming Project\ScheduleFile.csv";

        DataSet dataset = new DataSet();
        StreamReader sr = new StreamReader(fileName);

        dataset.Tables.Add(tableName);
        dataset.Tables[tableName].Columns.Add("Athlete Name");
        dataset.Tables[tableName].Columns.Add("Pace Per Mile");

        string allData = sr.ReadToEnd();
        string[] rows = allData.Split("\r".ToCharArray());

        foreach (string r in rows)
        {
            string[] items = r.Split(delimiter.ToCharArray());
            dataset.Tables[tableName].Rows.Add(items);
        }
        this.dataGridView1.DataSource = dataset.Tables[0].DefaultView;

    }

A button opens a window which contains fields to add a new entry to the csv file. This is how I am doing this:

private void AddToScheduleBtn_Click(object sender, EventArgs e)
    {

        string FileName = @"F:\A2 Computing\C# Programming Project\ScheduleFile.csv";

        string AthleteDetails = textBox1.Text + "," + textBox2.Text;

        File.AppendAllText(FileName, AthleteDetails);

        AddToSchedule.ActiveForm.Close();


    }

Although this works once, When I try and add another entry to my csv file again it says it is open in another process and the program crashes. When the data first appears in my datagridview, there is an empty row at the bottom which there shouldn't be. What is the best way of allowing me to re-use the process so I can append to the file more than once?

  • where are you `Flushing the file as well as Closing the File once you append the data` ? – MethodMan Feb 19 '15 at 15:04
  • i can only assume that im not, how would i do this? – George Boulton Feb 19 '15 at 15:09
  • you need to close the FileStream in your case it's `sr.Close();` but I would do `sr.Flush()` then call `sr.Close()` then call `sr.Dispose()` – MethodMan Feb 19 '15 at 15:14
  • You only need to flush when you write to a file and the File.AppendAllText does not return a FileStream object back. Internally it does dispose which in turn flushes and closes the stream. – Alex Mendez Feb 19 '15 at 15:18

2 Answers2

3

I think your line,

StreamReader sr = new StreamReader(fileName);

has the file opened. You want to do the following:

string allData = sr.ReadToEnd();
sr.Close();
sr.Dispose();
Alex Mendez
  • 5,120
  • 1
  • 25
  • 23
  • 1
    Or [File.ReadAllLines](https://msdn.microsoft.com/library/s2tte0y1.aspx) (corresponding to the already used `File.WriteAllLines`). – Corak Feb 19 '15 at 15:18
1

I didn't build your code, but this error is usually raised when the file reader was not closed :)

You should add sr.close() to your LoadAthletes method or implement the using for an automatic closing:

using (StreamReader sr = new StreamReader(fileName))
{
  allData = sr.ReadToEnd();
}

Or use the following method :

allData = File.ReadAllText(fileName);

Hope this Help

For more information see this question do-i-need-to-explicitly-close-the-streamreader-in-c-sharp-when-using-it-to-load

Community
  • 1
  • 1
Yahya
  • 501
  • 4
  • 8