在 Windows Server 2012 R2 系统上,Kotlin 程序使用 FileChannel.tryLock()
对一个文件持有独占锁,像这样:
val fileRw = RandomAccessFile(file, "rw")
fileRw.channel.tryLock()
有了这个锁,我不能打开文件:
- 写字板
- Notepad++
以编程方式使用 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(是的,我很绝望)
我可以用记事本打开它。
记事本怎么能打开锁定的文件,而其他任何东西都打不开?
最佳答案
记事本通过首先将文件映射到内存来读取文件,而不是使用您尝试过的其他编辑器可能使用的“常规”文件读取机制。此方法允许读取文件,即使它们具有基于范围的独占锁也是如此。
您可以通过以下方式在 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);
}
关于windows - 记事本打败了所有人?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45644934/