有没有办法从锁定的文件中读取数据?

时间:2012-06-20 15:42:23

标签: c# file file-io io

以下是我的想法:

        var file = @"myfile";
        File.Open(file,
                  FileMode.Open, FileAccess.ReadWrite, FileShare.None);

        using (StreamReader rdr = new StreamReader(File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read)))
        {
            rdr.ReadToEnd();
        }
        var t = File.ReadAllBytes(file);

Neigther File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read)File.ReadAllBytes可以读取文件数据。

从旧的c ++和winapi时代开始,我确实记得,如果你有备份权限,曾经有一种很好的方法来读取锁定的文件,但我不知道如何在c#中获取和使用它们。

任何人都可以向我提供有关如何在文件被锁定后读取文件的示例吗?

2 个答案:

答案 0 :(得分:6)

好吧,如果文件完全锁定(没有sharing),您将无法阅读它。如果文件已打开到share read,您将能够使用非侵入式方法阅读:

string fileName = @"myfile";
using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using (StreamReader fileReader = new StreamReader(fileStream ))
{
    while (!fileReader .EndOfStream)
    {
        string line = fileReader .ReadLine();
        // Your code here
    }
}

答案 1 :(得分:1)

我试图做的事实上是不可能的,而备份权限也无济于事:

       [DllImport("kernel32.dll", CharSet = CharSet.Auto,
        CallingConvention = CallingConvention.StdCall,
        SetLastError = true)]
            public static extern SafeFileHandle CreateFile(
                string lpFileName,
                uint dwDesiredAccess,
                uint dwShareMode,
                IntPtr SecurityAttributes,
                uint dwCreationDisposition,
                uint dwFlagsAndAttributes,
                IntPtr hTemplateFile
            );

    private static uint READ_CONTROL = 0x00020000;
    private static uint OPEN_EXISTING = 3;
    private static uint FILE_FLAG_BACKUP_SEMANTICS = 0x02000000;


        var file = @"myfile";
        File.Open(file,
                  FileMode.Open, FileAccess.ReadWrite, FileShare.None);

        using(PrivilegeEnabler pe = new PrivilegeEnabler(Process.GetCurrentProcess(), Privilege.Backup))
        {
            var hFile = CreateFile(file,           // lpFileName
                       READ_CONTROL,               // dwDesiredAccess
                       0,                          // dwShareMode
                       IntPtr.Zero,                // lpSecurityAttributes
                       OPEN_EXISTING,              // dwCreationDisposition
                       FILE_FLAG_BACKUP_SEMANTICS, // dwFlagsAndAttributes
                       IntPtr.Zero);               // hTemplateFile
            using (var fs=new  FileStream(hFile.DangerousGetHandle(),FileAccess.Read))
            {
                using (StreamReader rdr=new StreamReader(fs))
                {
                    rdr.ReadToEnd();
                }
            }
        }

仍然会导致错误。