在日常开发中,C#提供的System.IO.File和System.IO.Directory已经能覆盖大部分文件操作需求,但一旦遇到只读文件删除失败、路径超过260字符、需要监听复制进度这类场景,托管类库就显得力不从心了。这时就需要通过P/Invoke(Platform Invoke)技术直接调用Windows API,本文将结合文件操作的经典API,讲解声明、调用与错误处理的完整流程。

一、P/Invoke基础:DllImport声明怎么写
P/Invoke的核心是System.Runtime.InteropServices命名空间下的DllImport特性。通过它告诉CLR:某个托管方法实际上对应非托管DLL中的导出函数。Windows文件相关的API大多位于kernel32.dll中,声明时需要指定库路径(直接写DLL名即可,系统会自动搜索System32目录)。
一个最基本的声明如下:
using System.Runtime.InteropServices;
public class NativeFile
{
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool DeleteFile(string lpFileName);
}
这里有三个关键参数需要理解。SetLastError = true表示让CLR在API返回后保留线程的上一次错误码,这样后续可以用Marshal.GetLastWin32Error()拿到失败原因,如果不设置这个参数,拿到的错误码很可能是被其他调用污染过的脏数据。CharSet = CharSet.Unicode指定字符串按宽字符传递,Windows NT之后内核统一使用UTF-16,这里不写清楚可能在某些重名重载下出现乱码。参数string lpFileName会被自动封送为LPCWSTR,返回的bool对应API的BOOL类型。
还有一个容易忽略的细节:C#的bool在非托管签名不匹配时可能引发崩溃,某些API建议用int或[MarshalAs(UnmanagedType.Bool)]显式指定封送方式。对于文件API,保持bool加显式CharSet是相对稳妥的组合。
二、常用文件API的完整调用示例
1. 删除只读文件:DeleteFile配合SetFileAttributes
File.Delete遇到只读文件会直接抛异常,而原生做法是先改属性再删除:
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern bool SetFileAttributes(string lpFileName, uint dwFileAttributes);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern bool DeleteFile(string lpFileName);
const uint FILE_ATTRIBUTE_NORMAL = 0x80;
public static void ForceDelete(string path)
{
// 先去掉只读等特殊属性
if (!SetFileAttributes(path, FILE_ATTRIBUTE_NORMAL))
throw new System.ComponentModel.Win32Exception(
System.Runtime.InteropServices.Marshal.GetLastWin32Error());
if (!DeleteFile(path))
throw new System.ComponentModel.Win32Exception(
System.Runtime.InteropServices.Marshal.GetLastWin32Error());
}
Win32Exception会把错误码自动翻译成中文错误消息,比手动switch错误码方便得多。注意不要用Marshal.ThrowExceptionForHR,Win32错误码和HRESULT并不是一回事。
2. 带进度回调的复制:CopyFileEx
CopyFileEx支持取消复制和进度通知,这是托管API完全没有的能力。它需要传入一个回调函数委托:
using System.Runtime.InteropServices;
public delegate int CopyProgressRoutine(
long TotalFileSize, long TotalBytesTransferred,
long StreamSize, long StreamBytesTransferred,
uint dwStreamNumber, uint dwCallbackReason,
IntPtr hSourceFile, IntPtr hDestinationFile, IntPtr lpData);
public class FileCopier
{
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CopyFileEx(
string lpExistingFileName, string lpNewFileName,
CopyProgressRoutine lpProgressRoutine,
IntPtr lpData, ref bool pbCancel, uint dwCopyFlags);
static int OnProgress(long total, long transferred,
long streamSize, long streamTransferred,
uint streamNum, uint reason, IntPtr src, IntPtr dst, IntPtr data)
{
Console.WriteLine($"已复制 {transferred * 100 / total}%");
return 0; // 返回0继续复制,返回1终止
}
public static void CopyWithProgress(string src, string dst)
{
bool cancel = false;
bool ok = CopyFileEx(src, dst, OnProgress, IntPtr.Zero, ref cancel, 0);
if (!ok)
throw new System.ComponentModel.Win32Exception(
Marshal.GetLastWin32Error());
}
}
回调委托必须保存为字段或由P/Invoke层保持引用,否则在复制大文件期间委托可能被垃圾回收,导致回调时程序崩溃。这是P/Invoke回调最经典的坑,务必注意。
3. 重启后延迟替换:MoveFileEx
有些系统文件正在被占用,无法立即改名或替换,MoveFileEx的MOVEFILE_DELAY_UNTIL_REBOOT标志可以把操作排队到下次重启时执行:
const uint MOVEFILE_DELAY_UNTIL_REBOOT = 0x4;
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern bool MoveFileEx(string lpExistingFileName,
string lpNewFileName, uint dwFlags);
public static void ReplaceOnReboot(string src, string dst)
{
if (!MoveFileEx(src, dst, MOVEFILE_DELAY_UNTIL_REBOOT))
throw new System.ComponentModel.Win32Exception(
Marshal.GetLastWin32Error());
}
该标志需要管理员权限,排队信息记录在注册表HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager的PendingFileRenameOperations值中,感兴趣的读者可以自行验证。
三、长路径、错误处理与安全实践
Windows传统路径限制为260字符(MAX_PATH),如果程序要处理深层目录,可以在路径前加上\\?\前缀来突破限制,例如\\?\C:\Very\Long\Path\file.txt。注意使用该前缀时路径必须是绝对路径,且不能包含/斜杠和相对片段。从Windows 10 1607开始,也可以在注册表HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem中设置LongPathsEnabled为1,配合新版.NET运行时直接支持长路径,两种方式各有适用场景。
错误处理方面要养成固定习惯:声明API时一定加SetLastError = true,调用后立刻用Marshal.GetLastWin32Error()读取错误码,中间不要插入任何其他非托管调用。常见的错误码包括32(文件被占用,SHARING_VIOLATION)、3(路径不存在)、5(拒绝访问),拿到错误码后用Win32Exception包装抛出,方便上层统一捕获。
最后是安全性建议:所有来自用户的路径参数传给API前建议先Path.GetFullPath规范化,防止相对路径在不同工作目录下产生歧义;平台兼容方面,如果程序要在Linux上跑,建议用[SupportedOSPlatform("windows")]标注P/Invoke类,配合条件编译隔离平台代码;.NET 5之后还可以考虑源生成器[LibraryImport]代替DllImport,它在编译期生成封送代码,剪裁发布时更安全,性能也略有提升。
总的来说,P/Invoke并不神秘,把声明写对、把错误处理好、把委托生命周期管住,Windows文件API的绝大部分能力都能为C#所用。建议把所有声明集中到一个静态类中统一维护,遇到签名不确定的API时,官方文档和pinvoke.net都是可靠的参考来源。
P/InvokeC# Windows API文件操作修改时间:2026-09-07 21:14:42