.NET 中的 NTFS 备用数据流访问
操作 NTFS 备用数据流 (ADS) 对于各种场景(包括安全和数据)至关重要隐藏。 .NET 提供了读取和修改这些流的功能。
读取 ADS
要读取附加到文件的数据流,请使用 CreateFileW 函数:
using System.Runtime.InteropServices; public partial class NativeMethods { /// Return Type: HANDLE->void* ///lpFileName: LPCWSTR->WCHAR* ///dwDesiredAccess: DWORD->unsigned int ///dwShareMode: DWORD->unsigned int ///lpSecurityAttributes: LPSECURITY_ATTRIBUTES->_SECURITY_ATTRIBUTES* ///dwCreationDisposition: DWORD->unsigned int ///dwFlagsAndAttributes: DWORD->unsigned int ///hTemplateFile: HANDLE->void* [DllImportAttribute("kernel32.dll", EntryPoint = "CreateFileW")] public static extern System.IntPtr CreateFileW( [InAttribute()] [MarshalAsAttribute(UnmanagedType.LPWStr)] string lpFileName, uint dwDesiredAccess, uint dwShareMode, [InAttribute()] System.IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, [InAttribute()] System.IntPtr hTemplateFile ); }
使用文件名调用 CreateFileW,后跟流名称,并用冒号 (:) 分隔。例如:
var stream = NativeMethods.CreateFileW("testfile:stream", ...);
修改 ADS
要写入或修改流,只需使用返回的文件句柄来执行 I/O 操作。例如,要写入流:
using System.Runtime.InteropServices; class Program { static void Main(string[] args) { var stream = NativeMethods.CreateFileW("testfile:stream", ...); NativeMethods.WriteFile(stream, ...); } } public partial class NativeMethods { /// Return Type: BOOL->int ///hFile: HANDLE->void* ///lpBuffer: LPCVOID->void* ///nNumberOfBytesToWrite: DWORD->unsigned int ///lpNumberOfBytesWritten: LPDWORD->DWORD* ///lpOverlapped: LPOVERLAPPED->OVERLAPPED* [DllImportAttribute("kernel32.dll", EntryPoint = "WriteFile")] [return: MarshalAsAttribute(UnmanagedType.Bool)] public static extern bool WriteFile( [InAttribute()] System.IntPtr hFile, [InAttribute()] System.IntPtr lpBuffer, uint nNumberOfBytesToWrite, [OutAttribute()] [MarshalAsAttribute(UnmanagedType.U4)] out uint lpNumberOfBytesWritten, [InAttribute()] System.IntPtr lpOverlapped ); }
同样,您可以使用以下命令删除流:
using System.Runtime.InteropServices; class Program { static void Main(string[] args) { var stream = NativeMethods.CreateFileW("testfile:stream", ...); NativeMethods.DeleteFile(stream); } } public partial class NativeMethods { /// Return Type: BOOL->int ///lpFileName: LPCWSTR->WCHAR* [DllImportAttribute("kernel32.dll", EntryPoint = "DeleteFileW")] [return: MarshalAsAttribute(UnmanagedType.Bool)] public static extern bool DeleteFileW([InAttribute()] [MarshalAsAttribute(UnmanagedType.LPWStr)] string lpFileName); }
以上是如何在 .NET 中读取、写入和删除 NTFS 备用数据流?的详细内容。更多信息请关注PHP中文网其他相关文章!