Let’s say you want to open an Excel file by code but this Excel file is already opened by another user on another machine on a file share… You might encounter this issue: The process cannot access the file because it is being used by another process.

But you still can open this file in Excel! But not by code?!

Maybe because you’re not using the FileStream class correctly:

using (var file = new FileStream(fullFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
    byte[] bytes = new byte[file.Length];
    file.Read(bytes, 0, (int)file.Length);

    //do something with bytes (like sending it to the backend for processing...)
}
Code language: C# (cs)

Some remarks:

  • FileMode.Open
  • FileAccess.Read
  • FileShare.ReadWrite

Indeed, here we only want to get the data from this Excel file, so we only need to open it in read mode.

But without the FileShare.ReadWrite parameter, you will have an access denied on the file.

Happy coding, nerds! 😉