Question

I am trying to use a StreamReader to read a file, but it is always in use by another process so I get this error:

The process cannot access the file '\arfjwknasgmed17\C$\FLAG CONDITION\CP-ARFJN-FLAG.XLS' because it is being used by another process.

Is there a way I can read this without copying it? Or is that my only option?

Was it helpful?

Solution

You can read the file only if the program that opened the file first specified read sharing rights on that file.

If the file does indeed have no read sharing rights though, you wouldn't be able to copy it in the first place.

You may not be able to access a file if you are specifying a sharing right that conflicts with the sharing right of a program that already has the file opened. For example you can't grant write access if the program that already has it opened isn't granting write access.

If the program that opened the file in the first place supports Volume Shadow Copy (VSS), you can also use VSS to gain access to the file.

There are commercial software drivers that allow you to access such files, even when they are in use. You used to be able to get Open File Manager by St-Bernards, and you can also use File Access Manager (FAM) by VisionWorks Solutions Inc. These drivers are typically OEM'ed to backup software companies for inclusion in their products.

VSS works by telling the program that has the file opened already that another program would like to read from the file. VSS then does a copy of the file and lets you read from this copy. VSS does not work for legacy applications.

FAM transparently works for legacy and non-legacy programs alike by specifying an 'allowed list' of applications that can access exclusively opened and locked files. Only programs in this list are allowed access to these files. When a file is being opened, it goes into cache mode so that you will obtain a copy of the file as it was when the 'backup/open' of the file started. At this point the program that originally opened the file sees the file as it actually is, and the second program in the allowed list, sees the file as it was when the 'open/backup' of the file happened. This ensures consistency of the file.

OTHER TIPS

try the below code.

FileStream fileStr = File.Open(<full file name>, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
fileStream = new StreamReader(fileStr);

I have tried it on Windows XP. If the file is already open in write mode by some other process & it has not specified sharing rights, you will still be able to open the file in read mode.

Disclaimer: It works, but then, I am not sure if you should use it in production code. I am not yet able to find any formal documentation that says it should work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top