繁体   English   中英

与锁无关的文件只读访问 (C#)

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

如何打开(使用 c#)一个已经打开的文件(例如在 MS Word 中)? 我想如果我打开文件进行读取访问,例如

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

我应该成功,但我得到一个例外:

“该进程无法访问该文件,因为它已被锁定......”

我知道必须有一种方法可以读取文件,而不管文件上是否有任何锁定,因为我可以使用 Windows 资源管理器复制文件或使用记事本等其他程序打开它,即使它在 WORD 中打开也是如此。

但是,似乎 C# 中的 File IO 类都不允许我这样做。 为什么?

您想设置 FileAccess=Read 和 FileShare=ReadWrite。 这是一篇关于此的很棒的文章(以及原因的解释):

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

您的代码正在使用 FileAccess.Read*Write* 标志。 尝试只是阅读。

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

以资源管理器的方式复制锁定的文件。

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

使用示例

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM