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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With