要在C#中使用文件系统驱动程序隐藏目录,请遵循以下步骤:
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Principal;
namespace HideDirectory
{
class Program
{
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern IntPtr CreateFile(
string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile);
static void Main(string[] args)
{
string folderPath = @"C:\MyHiddenFolder";
try
{
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
HideFolder(folderPath);
Console.WriteLine($"Folder {folderPath} has been hidden.");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
static void HideFolder(string folderPath)
{
var folderInfo = new DirectoryInfo(folderPath);
var hFile = CreateFile(
folderInfo.FullName,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
IntPtr.Zero,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,
IntPtr.Zero);
if (hFile.ToInt32() != -1)
{
try
{
uint fileAttributes = GetFileAttributes(hFile);
fileAttributes |= FILE_ATTRIBUTE_HIDDEN;
SetFileAttributes(hFile, fileAttributes);
}
finally
{
CloseHandle(hFile);
}
}
}
const uint GENERIC_READ = 0x80000000;
const uint GENERIC_WRITE = 0x40000000;
const uint FILE_SHARE_READ = 0x00000001;
const uint FILE_SHARE_WRITE = 0x00000002;
const uint OPEN_EXISTING = 0x00000003;
const uint FILE_FLAG_BACKUP_SEMANTICS = 0x02000000;
const uint FILE_ATTRIBUTE_HIDDEN = 0x00000002;
[DllImport("kernel32.dll", SetLastError = true)]
static extern uint GetFileAttributes(IntPtr hFile);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool SetFileAttributes(IntPtr hFile, uint fileAttributes);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool CloseHandle(IntPtr hObject);
}
}
请注意,隐藏文件夹并不能完全保护它免受未经授权的访问。有经验的用户可能仍然能够找到并访问这些隐藏的文件夹。此外,隐藏文件夹可能在某些文件浏览器中无法正常工作。因此,请确保使用适当的安全措施来保护敏感数据。
领取专属 10元无门槛券
手把手带您无忧上云