Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot write to file while it is opened in MS Excel

I am writing to the text file some data. I am using this code:

  using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
  {
      using (TextWriter tw = new StreamWriter(fs))
      {
      tw.WriteLine("sample_data");
      }
   }

When file is opened by notepad my app can write into it. When this file is opened by MS Excel I get following error: The process cannot access the file myfile.csv because it is being used by another process. What can cause this situation and how can I solve this problem?

like image 694
user1013552 Avatar asked Feb 22 '23 07:02

user1013552


2 Answers

Notepad opens the file, reads in the entire contents and then closes the file. You can even delete the file that is open in notepad.

Excel on the other hand keeps the file open as long as it is displayed. There are some special sharing tools that can be enabled in Excel for excel format files. In that case I assume that it is opened non-exlusively. Otherwise Excel opens the file exclusively and keeps it open.

It doesn't matter that you specify a share option when opening, if the file is already opened by someone else in exclusive mode.

like image 72
Anders Abel Avatar answered Feb 24 '23 21:02

Anders Abel


Excel will lock the file when it is open which prevents interaction with the file. One way I worked around this is that I wrote code to scan for excel processes on the local machine and would kill those processes before accessing a file that was open with excel. You could determine if a file is locked by looking at How to check for file lock? and then running the process killing code in the exception handler.

like image 24
Peter Smith Avatar answered Feb 24 '23 20:02

Peter Smith