文件只读访问,无论锁定(C#)

时间:2011-05-10 02:24:26

标签: c# io

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

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

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

  

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

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

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

3 个答案:

答案 0 :(得分:7)

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

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

答案 1 :(得分:1)

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

答案 2 :(得分: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).GetCopy(@"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;
    }
}