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

Here is what I mean:

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) and File.ReadAllBytes can read file data.

From my old days of C ++ and winapi, I remember that there was a good way to read locked files if you have backup privileges, but I have no idea how to get and use them in C #.

Can someone provide me with a sample of how to read a file after it is locked?

+4
source share
2 answers

Well, if the file is completely locked (no sharing ), you will not be able to read it. If the file was opened for share read , you can read it using the 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 } } 
+6
source

What I'm actually trying to do is impossible, and backing up doesn't help:

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

still lead to an error.

+1
source

All Articles