-2

I am generating report in .csv file.

I am opening a .csv file through code on button click event using below code.

    StreamWriter sw = new StreamWriter(AbsolutePathAndFileName);

        //write header line
        int iColCount = TheDataTable.Columns.Count;
        for (int i = 0; i < iColCount; i++)
        {
            sw.Write(TheDataTable.Columns[i]);
            if (i < iColCount - 1)
            {
                sw.Write(separator);
            }
        }
        sw.Write(sw.NewLine);

        //write rows
        foreach (DataRow dr in TheDataTable.Rows)
        {
            for (int i = 0; i < iColCount; i++)
            {
                if (!Convert.IsDBNull(dr[i]))
                {
                    string data = dr[i].ToString();
                    data = data.Replace("\"", "\\\"").Replace(",", " ");
                    sw.Write(quote + data + quote);
                }
                if (i < iColCount - 1)
                {
                    sw.Write(separator);
                }
            }
            sw.Write(sw.NewLine);
        }
        sw.Close();



 MsgBox db = new MsgBox("Please select below option.", "Message", MessageBoxIcon.Information);
                db.SetButtons("Open Master File", "Save Master File", strBasePath + "\\master.csv");
                db.ShowDialog(this);

This code works fine for me.

Now my file is in open mode. If am filtering another criteria to open report again (.csv file) than it throws error to me that file is used by another process.

How can I solve that error ?

Lajja Thaker
  • 2,031
  • 8
  • 33
  • 53

1 Answers1

0

ChrisW has given a good answer on Is there a way to check if a file is in use?

You can check whether your file is in use or not, using this sample code:

protected virtual bool IsFileLocked(FileInfo file)
{
    FileStream stream = null;

    try
    {
        stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    }
    catch (IOException)
    {
        //the file is unavailable because it is:
        //still being written to
        //or being processed by another thread
        //or does not exist (has already been processed)
        return true;
    }
    finally
    {
        if (stream != null)
            stream.Close();
    }

    //file is not locked
    return false;
}

Hope this helps.

Community
  • 1
  • 1
talha2k
  • 24,937
  • 4
  • 62
  • 81
  • this code is not working for me. I got an exception from the line stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); in finally block condition is not satisfied .. as stream returns null to me – Lajja Thaker Aug 17 '12 at 06:59
  • you should update your question - it's a very important detail! What's the type,message of thrown Exception? – Konstantin Chernov Aug 17 '12 at 07:03