开发者

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

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?


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


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


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;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜