Is there any way to read data from a locked file?

后端 未结 2 544

Here\'s what I have in mind:

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


        
相关标签:
2条回答
  • 2021-01-19 06:06

    What I was trying to do in fact is impossible, and backup privilege doesn't help either:

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

    will still result in an error.

    0 讨论(0)
  • 2021-01-19 06:10

    Well, if the file is totally locked (no sharing) you will not be able to read it. If the file was opened to share read, you will be able to read using a non intrusive method:

    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
        }
    }
    
    0 讨论(0)
提交回复
热议问题