简体   繁体   中英

How to prevent locking of a shared file while it is being read/written in C#?

I have a desktop application and below is the flow that is to be followed. During app initialization, an API should be hit and an excel should downloaded to a shared location. After download is complete the app should read the excel file. This won't be a problem with a single instance of app running. But since this is a desktop app, multiple instances (on different computers) are run, app every time during initialization, downloads the file. I'm using OLE Db engine to read the file and the file is being locked and there 's error "The ole db engine cannot read the file because it is opened by another user " while another instance of the app is opened. How to prevent this?

if (response.Result.IsSuccessStatusCode)
                    {
                        using (Stream streamToWriteTo = new FileStream(pathToDownloadReport, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        {
                            response.Result.Content.CopyToAsync(streamToWriteTo).Wait();
                        }
                    }

If you want to have concurrent access to a file you need to make sure every client only takes a read-lock on the file. With OleDb you can open a connection to the file with ReadOnly access with a connection.

"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\path\to\your\exelfile.xlsx;Extended Properties=\"Excel 12.0;IMEX=1;ReadOnly=true;\""

You still need to make sure no one opens the file in Excel.

Since you only can have read-only access to your file, you might as well make a local copy of the file and open that instead. That way locking won't be a problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM