.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中文網其他相關文章!