0

It is possible to use a FileShare value of FileShare.ReadWrite to open a file for reading, while it is already open in other programs (e.g. like Excel). e.g.:

  using (FileStream fs = new FileStream(@"c:\abd\somefile.xlsx",
                  FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  {
      // read file, etc.
  }

Just wondering if this a good idea. e.g. in worst case, what will happen if the external program is writing to the file, and your code is trying to read it at the same time ?

I have noticed libraries like spreadsheet gear that can read files even when they are open in Excel - are they basically hoping that they will be able to read the whole file into memory before any part of it is changed ?

Moe Sisko
  • 11,665
  • 8
  • 50
  • 80
  • you can get your answer in the following links (https://stackoverflow.com/questions/25097773/system-io-filestream-fileaccess-vs-fileshare), (https://stackoverflow.com/questions/222089/in-c-if-2-processes-are-reading-and-writing-to-the-same-file-what-is-the-best) – Harsh Kumar Jun 02 '17 at 07:52
  • What happens if you open a file already opened by another program depends from program to program. Some programs will load the file in memory, while others will directly read/write from/to the file itself. From my understanding of Excel, when you open a file, it write-locks that file and also creates an "Owner File" with a similar name (`~$filename.xlsx`) that is used to tell other users that you're currently editing the file. Excel doesn't actually read-lock the file, though, in order for other users to be able to copy the file and edit their copy of it. – Pierre-Loup Pagniez Jun 02 '17 at 07:55
  • You can read e.g. [this question and its answer](https://stackoverflow.com/questions/222089/in-c-if-2-processes-are-reading-and-writing-to-the-same-file-what-is-the-best). Generally speaking, there is always a risk to read an incomplete file if two or more processes open the same file (even using access sharing). – dymanoid Jun 02 '17 at 08:04

0 Answers0