C#如何调用Windows系统自身的文件复制功能,显示文件进度,显示重名提示
我们知道在.Net中要实现普通的文件复制功能很简单。File.Copy(src, dest)就可以完成。
如果需要显示复制文件的进度,如下图:
如果需要处理文件重名问题,如下图:
难道我们还需要自己编程一套逻辑和界面来完成以上功能吗?
这些问题Windows系统自身已经帮我们解决了,我们可以直接使用系统的文件复制功能来完成。
主要通过windows API:SHFileOperation 来实现
通过PInvoke转C#代码如下:
public class Win32 { public enum FileFuncFlags : uint { FO_MOVE = 0x1, FO_COPY = 0x2, FO_DELETE = 0x3, FO_RENAME = 0x4 } [Flags] public enum FILEOP_FLAGS : ushort { FOF_MULTIDESTFILES = 0x1, FOF_CONFIRMMOUSE = 0x2, FOF_SILENT = 0x4, FOF_RENAMEONCOLLISION = 0x8, FOF_NOCONFIRMATION = 0x10, FOF_WANTMAPPINGHANDLE = 0x20, FOF_ALLOWUNDO = 0x40, FOF_FILESONLY = 0x80, FOF_SIMPLEPROGRESS = 0x100, FOF_NOCONFIRMMKDIR = 0x200, FOF_NOERRORUI = 0x400, FOF_NOCOPYSECURITYATTRIBS = 0x800, FOF_NORECURSION = 0x1000, FOF_NO_CONNECTED_ELEMENTS = 0x2000, FOF_WANTNUKEWARNING = 0x4000, FOF_NORECURSEREPARSE = 0x8000 } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct SHFILEOPSTRUCT { public IntPtr hwnd; public FileFuncFlags wFunc; [MarshalAs(UnmanagedType.LPWStr)] public string pFrom; [MarshalAs(UnmanagedType.LPWStr)] public string pTo; public FILEOP_FLAGS fFlags; [MarshalAs(UnmanagedType.Bool)] public bool fAnyOperationsAborted; public IntPtr hNameMappings; [MarshalAs(UnmanagedType.LPWStr)] public string lpszProgressTitle; } [DllImport("shell32.dll", CharSet = CharSet.Unicode)] public static extern int SHFileOperation([In] ref SHFILEOPSTRUCT lpFileOp); }
调用步骤:
Win32.SHFILEOPSTRUCT op = new Win32.SHFILEOPSTRUCT();
op.hwnd = IntPtr.Zero;
op.wFunc = Win32.FileFuncFlags.FO_COPY;
op.pFrom = SrcTextBox.Text + "\0";// 需要注意,最后需要加入"\0"表示字符串结束,如果需要拷贝多个文件,则 file1 + "\0" + file2 + "\0"...
op.pTo = DestTextBox.Text + "\0";// 需要注意,最后需要加入"\0"表示字符串结束
op.hNameMappings = IntPtr.Zero;
op.fFlags = Win32.FILEOP_FLAGS.FOF_NOCONFIRMMKDIR;
op.fAnyOperationsAborted = false;
int ret = Win32.SHFileOperation(ref op);
return ret == 0;