简体   繁体   English

锁定文件块

[英]Lock a block of a file

I have a file that is 192k in size, I want to lock the middle of the file. 我有一个大小为192k的文件,我想锁定文件的中间位置。

Ex) I would like to lock 64k-128k of the file with c#. 例)我想用c#锁定64k-128k的文件。 Any idea how I would lock that part of the file? 知道如何锁定文件的那部分吗?

You'll need to use LockFileEx 您需要使用LockFileEx

Locks the specified file for exclusive access by the calling process. 锁定指定的文件以供调用进程独占访问。 This function can operate either synchronously or asynchronously and can request either an exclusive or a shared lock. 此功能可以同步或异步操作,并可以请求独占锁或共享锁。

You're looking for a shared lock. 你正在寻找共享锁。

[DllImport("kernel32.dll")]
static extern bool LockFileEx(IntPtr hFile, uint dwFlags, uint dwReserved,
   uint nNumberOfBytesToLockLow, uint nNumberOfBytesToLockHigh,
   [In] ref System.Threading.NativeOverlapped lpOverlapped);

You might want to look into the LockFile function in the Windows API. 您可能希望查看Windows API中的LockFile函数。 The same page also mentions a LockFileEx function. 同一页面还提到了LockFileEx函数。 Yay! 好极了! Have tons of fun mucking around ;) 周围有很多乐趣;)

The pinvoke site has a page on it: http://www.pinvoke.net/default.aspx/kernel32.lockfile pinvoke网站上有一个页面: http//www.pinvoke.net/default.aspx/kernel32.lockfile

You cant lock parts of a file using System.IO . 您无法使用System.IO锁定文件的某些部分。 If you have a open handle on the file, the complete file is locked. 如果文件上有打开的句柄,则会锁定整个文件。

You can do this using WinAPI. 您可以使用WinAPI执行此操作。

Check out Using LockFileEX in C# 在C#中查看使用LockFileEX

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM