user1013552
user1013552

Reputation: 313

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?

Upvotes: 4

Views: 2101

Answers (3)

AMissico
AMissico

Reputation: 21684

Open the csv file using OleDB and use INSERT and/or UPDATE statements.

Upvotes: -1

Anders Abel
Anders Abel

Reputation: 69260

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.

Upvotes: 8

Peter Smith
Peter Smith

Reputation: 889

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.

Upvotes: 1

Related Questions