Home » excel » c# – Kill Locks on Excel or Csv file

c# – Kill Locks on Excel or Csv file

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a procedure that loops over a collection of excel and csv file and pulls the data back into a datatable for processing:

    public static DataTable Get(string path, bool IsFirstRowHeader)
    {
        var header = "No";
        var sql = string.Empty;
        DataTable dataTable = null;
        var pathOnly = string.Empty;
        var fileName = string.Empty;

        try
        {
            pathOnly = Path.GetDirectoryName(path);
            fileName = Path.GetFileName(path);

            sql = @"SELECT * FROM [" + fileName + "]";

            if (IsFirstRowHeader) { header = "Yes"; }

            using (var connection = new   OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly + ";Extended   Properties='Excel 8.0;HDR=YES;IMEX=1;';"))
            {
                using (var command = new OleDbCommand(sql, connection))
                {
                    using (var adapter = new OleDbDataAdapter(command))
                    {
                        dataTable = new DataTable {Locale =   CultureInfo.CurrentCulture};
                        adapter.Fill(dataTable);
                    }
                }
            }
        }
        catch(Exception ex)
        {
            ErrorLog.Log();
        }

        return dataTable;
    }

However if a user is viewing this I get the following error:

The Microsoft Jet database engine cannot open the file
'\cjserver\IS_CalendarImport\Staging-03-13done'.  It is already opened exclusively 
by another user, or you need permission to view its data.

Is there a way (preferably in code, C#) to release or circumvent the lock automatically ?

How to&Answers:

In theory, walking through windows internal functions, etc. yes could do kill the lock — in fact, the unlocker utility does just that. However, in the general case, this is unwise as programs don’t expect locks to magically disappear due to an outside process.

Testing the file to see if you can open it before trying to use it is a good strategy (try to open the file directly in your c# code).

If you can’t open the file in your c# code, you can follow one the following strategies:

1) Just skip the file — and maybe information user, admin, etc. of the skipped file
2) Retry the file later, revert to skipping killing after too many retries without success
3) As I was typing, I saw DarrenMB has already suggested copying the file — and using the copy instead.

Answer:

Don’t know how to circumvent the lock with Jet (may not be possible) but you can copy the file while it’s in use in most cases.

So an easy workaround is to copy the file into a temp directory and query your data against the temp file.