The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

    • RT @michaelbolton: 1) Your periodic reminder: a test is not something we *write*. We write text and programs. A test is an experiment you *… 2 hours ago
    • RT @BiancaPrins: Voor ons allemaal, een #draadje om tot het einde te lezen..... Juist nu (Volgt nog meer in de komende dagen)… 2 hours ago
    • RT @McKayMSmith: 90) His entire life, Ben has chosen to place his faith in the law. “Law, not war” has been his motto for decades. “I hav… 2 hours ago
    • RT @McKayMSmith: 82) “It's possible to take the most fundamental, strongly held ideas and change them. What makes people change? Sometimes… 2 hours ago
    • RT @McKayMSmith: 65) “Now I will tell you something very profound, which I have learned after many years. War makes murderers out of otherw… 2 hours ago
  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 1,640 other followers

Reading files that are locked by other references: c# – Notepad beats them all? – Stack Overflow

Posted by jpluimers on 2018/08/16

Cool feature borrowed from Notepad, which can read files locked by other references (for instance a process having the handle open): [WayBackc# – Notepad beats them all? – Stack Overflow.

The example from the answer is in .NET, but can be used in a native environment as well (Notepad is a native application).

Notepad reads files by first mapping them into memory, rather than using the “usual” file reading mechanisms presumably used by the other editors you tried. This method allows reading of files even if they have an exclusive range-based locks.

You can achieve the same in C# with something along the lines of:

using (var f = new FileStream(processIdPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var m = MemoryMappedFile.CreateFromFile(f, null, 0, MemoryMappedFileAccess.Read, null, HandleInheritability.None, true))
using (var s = m.CreateViewStream(0, 0, MemoryMappedFileAccess.Read))
using (var r = new StreamReader(s))
    var l = r.ReadToEnd();

Via: [WayBack] Maintaining Notepad is not a full-time job, but it’s not an empty job either – The Old New Thing


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: