Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File Read-only access irrespective of locks (C#)

Tags:

c#

io

How do I open (using c#) a file that is already open (in MS Word, for instance)? I thought if I open the file for read access e.g.

FileStream f= new FileStream('filename', FileMode.Open, FileAccess.ReadWrite);

I should succeed, but I get an exception:

"the process cannot access the file because it is locked ..."

I know there must be a way to read the file irrespective of any locks placed on it, because I can use windows explorer to copy the file or open it using another program like Notepad, even while it is open in WORD.

However, it seems none of the File IO classes in C# allows me to do this. Why?

like image 539
prmph Avatar asked May 10 '11 02:05

prmph


3 Answers

You want to set FileAccess=Read and FileShare=ReadWrite. Here is a great article on this (along with an explanation of why):

http://coding.infoconex.com/post/2009/04/How-do-I-open-a-file-that-is-in-use-in-C.aspx

like image 80
IAmTimCorey Avatar answered Oct 28 '22 02:10

IAmTimCorey


Your code is using the FileAccess.Read*Write* flag. Try just Read.

like image 25
dlev Avatar answered Oct 28 '22 02:10

dlev


I know this is an old post. But I needed this and I think this answer can help others.

Copying a locked file the way the explorer does it.

Try using this extension method to get a copy of the locked file.

Usage example

private static void Main(string[] args)
    {
        try
        {
            // Locked File
            var lockedFile = @"C:\Users\username\Documents\test.ext";

            // Lets copy this locked file and read the contents
            var unlockedCopy = new 
            FileInfo(lockedFile).CopyLocked(@"C:\Users\username\Documents\test-copy.ext");

            // Open file with default app to show we can read the info.
            Process.Start(unlockedCopy);
        }
        catch (Exception ex)
        {
            Trace.TraceError(ex.Message);
        }
    }

Extension method

internal static class LockedFiles
{
    /// <summary>
    /// Makes a copy of a file that was locked for usage in an other host application.
    /// </summary>
    /// <returns> String with path to the file. </returns>
    public static string CopyLocked(this FileInfo sourceFile, string copyTartget = null)
    {
        if (sourceFile is null)
            throw new ArgumentNullException(nameof(sourceFile));
        if (!sourceFile.Exists)
            throw new InvalidOperationException($"Parameter {nameof(sourceFile)}: File should already exist!");

        if (string.IsNullOrWhiteSpace(copyTartget))
            copyTartget = Path.GetTempFileName();

        using (var inputFile = new FileStream(sourceFile.FullName, FileMode.Open, 
        FileAccess.Read, FileShare.ReadWrite))
        using (var outputFile = new FileStream(copyTartget, FileMode.Create))
            inputFile.CopyTo(outputFile, 0x10000);

        return copyTartget;
    }
}
like image 31
generic-user Avatar answered Oct 28 '22 03:10

generic-user