Question

I am using the elency solutions CSV library for C# to save and load some data from a file.

My code saves and loads correctly, but when I load and then try to save an error occurs, saying that another process is using the file.

The load method is this:

private void loadfile(string name)
{
    int key = 696969;
    CsvReader read = new CsvReader("data.csv");

    try
    {
        do
        {
            read.ReadNextRecord();
        } while (name != read.Fields[0]);
        int decAgain = int.Parse(read.Fields[1], System.Globalization.NumberStyles.HexNumber); //convert to int
        int dec = decAgain ^ key;
        MessageBox.Show(dec.ToString());

    }
    catch (Exception)
    {
        MessageBox.Show("Not Found");
    }
        read = null;

}

As you can see, I am sort of disposing the "read" object.

Here is the save method:

private void savefile(string encrypted, string name)
{
    CsvFile file = new CsvFile();
    CsvRecord rec = new CsvRecord();
    CsvWriter write = new CsvWriter();

    rec.Fields.Add(name);
    rec.Fields.Add(encrypted);

    file.Records.Add(rec);
    write.AppendCsv(file, "data.csv");

    file = null;
    rec = null;
    write = null;

}

It always gets stuck on append csv. I do understand the problem. The reader is not being closed successfully. How can I correctly close the file?

NB: I have tried read.Dispose() but it is not working.

Can you please help me out?

Regards

Was it helpful?

Solution

Use using to automatically dispose object. It may solve your issue.

private void savefile(string encrypted, string name)
{
    using(CsvFile file = new CsvFile())
    {
        using(CsvRecord rec = new CsvRecord())
        {
            using(CsvWriter write = new CsvWriter())
            {

                rec.Fields.Add(name);
                rec.Fields.Add(encrypted);

                file.Records.Add(rec);
                write.AppendCsv(file, "data.csv");
            }
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top