windows 记事本打败了他们?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45644934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 19:55:59  来源:igfitidea点击:

Notepad beats them all?

windowslockingnotepadfile-accessfile-locking

提问by MonoThreaded

On a Windows Server 2012 R2 system, a Kotlin program uses FileChannel.tryLock()to hold an exclusive lock on a file, like this:

在 Windows Server 2012 R2 系统上,Kotlin 程序使用FileChannel.tryLock()排他锁持有文件,如下所示:

val fileRw = RandomAccessFile(file, "rw")
fileRw.channel.tryLock()

With this lock in place, I cannotopen the file with:

有了这个锁,我就无法打开文件:

  • WordPad
  • Notepad++
  • Programmatically with C#, for any value of FileShare:

    using (var fileStream = new FileStream(processIdPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    using (var textReader = new StreamReader(fileStream))
    {
        textReader.ReadToEnd();
    }
    
  • From the command line, the typecommand:

    C:\some-directory>type file.txt
    The process cannot access the file because another process has locked a portion of the file.
    
  • Internet Explorer (yes, I was desperate)

  • 写字板
  • 记事本++
  • 使用 C# 以编程方式,对于任何值FileShare

    using (var fileStream = new FileStream(processIdPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    using (var textReader = new StreamReader(fileStream))
    {
        textReader.ReadToEnd();
    }
    
  • 从命令行,type命令:

    C:\some-directory>type file.txt
    The process cannot access the file because another process has locked a portion of the file.
    
  • Internet Explorer(是的,我很绝望)

I canopen it with Notepad.

可以用记事本打开它。

How the heck is Notepad able to open a locked file that nothing else can?

记事本怎么能打开一个其他东西都不能打开的锁定文件?

回答by Iridium

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:

您可以通过以下方式在 C# 中实现相同的功能:

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();
    Console.WriteLine(l);
}