无论锁定状态,如何实现C#中的文件只读访问

7

我应该如何使用C#打开已经在MS Word中打开的文件?我想如果我以只读方式打开文件,例如

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

我应该会成功,但是我遇到了一个异常:

"进程无法访问文件,因为它被锁定..."

我知道一定有一种方法可以读取文件,而不受任何锁定的影响,因为我可以使用Windows资源管理器复制文件或者使用其他程序(如记事本)打开它,即使它在WORD中打开。

然而,似乎C#中的File IO类都不能实现这一点。为什么呢?

3个回答

7

1

你的代码正在使用 FileAccess.Read*Write* 标志。尝试只使用 Read。


抱歉,实际上我正在使用 FileAccess.Read。 - prmph

1

我知道这是一篇旧文章,但我需要它,我认为这个答案可以帮助其他人。

像资源管理器一样复制锁定的文件。

尝试使用这个扩展方法来获取锁定文件的副本。

使用示例

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

扩展方法
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;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接