SHFileOperation方法拷贝文件

时间:2022-03-25 21:38:00

 

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
          
            CopyDir(@"C:\Users\Geny\Desktop\TSSS-4979\DTSPOS", @"C:\Users\Geny\Desktop\TSSS-4979\Result");
            Console.WriteLine("Completed.");
            Console.ReadKey();


        }

        public static void CopyDir(string srcPath, string aimPath)
        {
            try
            {
                // 检查目标目录是否以目录分割字符结束如果不是则添加
                if (aimPath[aimPath.Length - 1] != System.IO.Path.DirectorySeparatorChar)
                {
                    aimPath += System.IO.Path.DirectorySeparatorChar;
                }
                // 判断目标目录是否存在如果不存在则新建
                if (!System.IO.Directory.Exists(aimPath))
                {
                    System.IO.Directory.CreateDirectory(aimPath);
                }
                // 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
                // 如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
                // string[] fileList = Directory.GetFiles(srcPath);
                string[] fileList = System.IO.Directory.GetFileSystemEntries(srcPath);
                // 遍历所有的文件和目录
                foreach (string file in fileList)
                {
                    // 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
                    if (System.IO.Directory.Exists(file))
                    {
                        if (file != "C:\\DTSPOS\\DATA")
                        {
                            //CopyDir(file, aimPath + System.IO.Path.GetFileName(file));
                            ShellFiles.Copy(file, aimPath);
                        }

                    }
                    // 否则直接Copy文件
                    else
                    {
                        //System.IO.File.Copy(file, aimPath + System.IO.Path.GetFileName(file), true);
                        ShellFiles.Copy(file, aimPath);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }      
    }
    public class ShellFiles
    {
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 1)]
        public struct SHFILEOPSTRUCT
        {
            public IntPtr hwnd;
            public UInt32 wFunc;
            public IntPtr pFrom;
            public IntPtr pTo;
            public UInt16 fFlags;
            public Int32 fAnyOperationsAborted;
            public IntPtr hNameMappings;
            [MarshalAs(UnmanagedType.LPWStr)]
            public string lpszProgressTitle;
        }

        [DllImport("shell32.dll", CharSet = CharSet.Auto)]
        static extern int SHFileOperation(ref SHFILEOPSTRUCT FileOp);
        const int FO_DELETE = 3;
        const int FO_COPY = 2;
        const int FOF_ALLOWUNDO = 0x40;
        const int FOF_NOCONFIRMATION = 0x10; //Don't prompt the user.;
        const int FOF_SIMPLEPROGRESS = 0x100;

        public static void Copy(string from, string to)
        {

            DirectoryInfo source = new DirectoryInfo(from);
            DirectoryInfo dest = new DirectoryInfo(to);

            if (!dest.Exists)
                dest.Create();

            SHFILEOPSTRUCT shf = new SHFILEOPSTRUCT();
            shf.wFunc = FO_COPY;
            //shf.fFlags = FOF_ALLOWUNDO;
            shf.fFlags = FOF_NOCONFIRMATION;//这个参数可以覆盖文件

     shf.pFrom = FileOP1(from);
            shf.pTo = FileOP2(to);
            SHFileOperation(ref shf);
        }

        private static IntPtr FileOP1(string sourceFile)
        {
            sourceFile += "\0\0";
            return Marshal.StringToHGlobalUni(sourceFile);
        }

        private static IntPtr FileOP2(string destFile)
        {
            destFile += "\0\0";
            return Marshal.StringToHGlobalUni(destFile);
        }
    }
}

 

 

 

//=============================================================

  1. SHFileOperation
  2. 函数功能描述:文件操作,与 Shell 的动作相同.
  3. 函数原型:
  4. #include<shellapi.h>
  5. WINSHELLAPI int WINAPI SHFileOperation(LPSHFILEOPSTRUCT lpFileOp);
  6. 参数:
  7. typedef struct _SHFILEOPSTRUCT
  8. {
  9. HWND hwnd; //父窗口句柄
  10. UINT wFunc; //要执行的动作
  11. LPCTSTR pFrom; //源文件路径,可以是多个文件
  12. LPCTSTR pTo; //目标路径,可以是路径或文件名
  13. FILEOP_FLAGS fFlags; //标志,附加选项
  14. BOOL fAnyOperationsAborted; //是否可被中断
  15. LPVOID hNameMappings; //文件映射名字,可在其它 Shell 函数中使用
  16. LPCTSTR lpszProgressTitle; // 只在 FOF_SIMPLEPROGRESS 时,指定对话框的标题。
  17. } SHFILEOPSTRUCT, FAR *LPSHFILEOPSTRUCT;
  18. =======================
  19. wFunc 可以为:
  20. /FO_MOVE 0x0001 移动文件
  21. FO_COPY 0x0002 复制文件
  22. FO_DELETE 0x0003 删除文件,只使用 pFrom
  23. FO_RENAME 0x0004 文件重命名
  24. fFlags可以为:
  25. FOF_MULTIDESTFILES 0x0001 //pTo 指定了多个目标文件,而不是单个目录
  26. FOF_CONFIRMMOUSE 0x0002
  27. FOF_SILENT 0x00044 // 不显示一个进度对话框
  28. FOF_RENAMEONCOLLISION 0x0008 // 碰到有抵触的名字时,自动分配前缀
  29. FOF_NOCONFIRMATION 0x0010 // 不对用户显示提示
  30. FOF_WANTMAPPINGHANDLE 0x0020 // 填充 hNameMappings 字段,必须使用 SHFreeNameMappings 释放
  31. FOF_ALLOWUNDO 0x0040 // 允许撤销
  32. FOF_FILESONLY 0x0080 // 使用 *.* 时, 只对文件操作
  33. FOF_SIMPLEPROGRESS 0x0100 // 简单进度条,意味者不显示文件名。
  34. FOF_NOCONFIRMMKDIR 0x0200 // 建新目录时不需要用户确定
  35. FOF_NOERRORUI 0x0400 // 不显示出错用户界面
  36. FOF_NOCOPYSECURITYATTRIBS 0x0800 // 不复制 NT 文件的安全属性
  37. FOF_NORECURSION 0x1000 // 不递归目录
  38. 返回值:
  39. 函数成功返回 0 ,失败返回非 0 。
  40. 例子:
  41. 1. 将 C:\Test.txt 拷贝到 D:\
  42. SHFILEOPSTRUCT lpsh;
  43. ZeroMemory(&lpsh,sizeof(lpsh));
  44. lpsh.hwnd= HWND_DESKTOP;
  45. lpsh.fFlags=FOF_NOCONFIRMATION|FOF_SIMPLEPROGRESS ;
  46. lpsh.wFunc=FO_COPY; // FO_MOVE 则是移动
  47. lpsh.pFrom= "C:\Test.txt";
  48. lpsh.pTo = "D:\"
  49. if( 0 != SHFileOperation(&lpsh))
  50. {
  51. AfxMessageBox("复制文件出错,请检查");
  52. return ;
  53. }
  54. 2. 删除 D:\Test.txt
  55. SHFILEOPSTRUCT lpsh;
  56. ZeroMemory(&lpsh,sizeof(lpsh));
  57. lpsh.hwnd= HWND_DESKTOP;
  58. lpsh.fFlags=FOF_NOCONFIRMATION|FOF_SIMPLEPROGRESS ;
  59. lpsh.wFunc=FO_DELETE;
  60. lpsh.pFrom= "D:\Test.txt";
  61. if( 0 != SHFileOperation(&lpsh))
  62. {
  63. AfxMessageBox("删除文件出错,请检查");
  64. return ;
  65. }
  66. 3.重命名
  67. SHFILEOPSTRUCT lpsh;
  68. ZeroMemory(&lpsh,sizeof(lpsh));
  69. lpsh.hwnd= HWND_DESKTOP;
  70. lpsh.fFlags=FOF_NOCONFIRMATION|FOF_SIMPLEPROGRESS ;
  71. lpsh.wFunc=FO_RENAME;
  72. lpsh.pFrom= "D:\Test.txt";
  73. lpsh.pTo = "D:\Test2.txt";
  74. if( 0 != SHFileOperation(&lpsh))
  75. {
  76. AfxMessageBox("重命名文件出错!");
  77. return ;
  78. }
  79. 注意事项
  80. 参数pTo、pFrom必须是以 双0 结束的,原文为:
  81. pFrom
  82. Pointer to a buffer that specifies one or more source file names. Multiple names must be null-separated. The list of names must be double null-terminated.
  83. a.如果是直接赋值:
  84. WCHAR strSrc[MAX_PATH] = _T("g:\\123");
    WCHAR strDst[MAX_PATH] = _T("g:\\456");
  85. 这样就可以成功编译。
  86. b.如果pTo、pFrom从CString获得,则:
  87. WCHAR SrcFolder[MAX_PATH],DestFolder[MAX_PATH];
  88. wcscpy_s(SrcFolder, Source);
    wcscpy_s(DestFolder,m_Path);
    SrcFolder[wcslen(SrcFolder) + 1] = 0;
    DestFolder[wcslen(DestFolder) + 1] = 0;
    (其中,Source与m_Path是在其他地方获取的值)
  89. 造成这种差异的原因是:CString在结尾并没有"\0",所以需要我们添加。
  90. 4.VB
  91. Public Declare Function SHFileOperation Lib "shell32.dll" Alias "SHFileOperationA" (lpFileOp As SHFILEOPSTRUCT) As Long
  92. Public Const FO_COPY = &H2
  93. Public Const FOF_ALLOWUNDO = &H40
  94. Public Sub ShellCopyFile(Source As String, Dest As String)
  95. Dim result As Long
  96. Dim fileop As SHFILEOPSTRUCT
  97. With fileop
  98. .hwnd = 0
  99. .wFunc = FO_COPY
  100. .pFrom = Source & vbNullChar & vbNullChar
  101. .pTo = Dest & vbNullChar & vbNullChar
  102. .fFlags = FOF_ALLOWUNDO
  103. End With
  104. result = SHFileOperation(fileop)
  105. If result <> 0 Then
  106. 'Msgbox the error that occurred in the API.
  107. MsgBox Err.LastDllError, vbCritical Or vbOKOnly
  108. Else
  109. If fileop.fAnyOperationsAborted <> 0 Then
  110. MsgBox "Operation Failed", vbCritical Or vbOKOnly
  111. End If
  112. End If
  113. End Sub
SHFileOperation

函数功能描述:文件操作,与 Shell 的动作相同.

函数原型:

#include<shellapi.h>

WINSHELLAPI int WINAPI SHFileOperation(LPSHFILEOPSTRUCT lpFileOp);

参数:

typedef struct _SHFILEOPSTRUCT

{

HWND hwnd; //父窗口句柄

UINT wFunc; //要执行的动作

LPCTSTR pFrom; //源文件路径,可以是多个文件

LPCTSTR pTo; //目标路径,可以是路径或文件名

FILEOP_FLAGS fFlags; //标志,附加选项

BOOL fAnyOperationsAborted; //是否可被中断

LPVOID hNameMappings; //文件映射名字,可在其它 Shell 函数中使用

LPCTSTR lpszProgressTitle; // 只在 FOF_SIMPLEPROGRESS 时,指定对话框的标题。

} SHFILEOPSTRUCT, FAR *LPSHFILEOPSTRUCT;

===================

vb.net

Public Structure SHFILEOPSTRUCT

Dim hwnd As IntPtr

Dim wFunc As Integer

Dim pFrom As String

Dim pTo As String

Dim fFlags As Short

Dim fAnyOperationsAborted As Integer

Dim hNameMappings As IntPtr

Dim lpszProgressTitle As String

End Structure

Public Declare Function SHFileOperation Lib "shell32.dll" Alias "SHFileOperationA" (ByRef lpFileOp As SHFILEOPSTRUCT) As Integer

======================

vb:

Type SHFILEOPSTRUCT

hWnd As Long

wFunc As Long

pFrom As String '必须用 pFrom & vbNullChar & vbNullChar

pTo As String '同pFrom

fFlags As Integer

fAnyOperationsAborted As Boolean

hNameMappings As Long

lpszProgressTitle As String

End Type

Public Declare Function SHFileOperation Lib "shell32.dll" Alias "SHFileOperationA" (lpFileOp As SHFILEOPSTRUCT) As Long

=======================

wFunc 可以为:

/FO_MOVE 0x0001 移动文件

FO_COPY 0x0002 复制文件

FO_DELETE 0x0003 删除文件,只使用 pFrom

FO_RENAME 0x0004 文件重命名

fFlags可以为:

FOF_MULTIDESTFILES 0x0001 //pTo 指定了多个目标文件,而不是单个目录

FOF_CONFIRMMOUSE 0x0002

FOF_SILENT 0x00044 // 不显示一个进度对话框

FOF_RENAMEONCOLLISION 0x0008 // 碰到有抵触的名字时,自动分配前缀

FOF_NOCONFIRMATION 0x0010 // 不对用户显示提示

FOF_WANTMAPPINGHANDLE 0x0020 // 填充 hNameMappings 字段,必须使用 SHFreeNameMappings 释放

FOF_ALLOWUNDO 0x0040 // 允许撤销

FOF_FILESONLY 0x0080 // 使用 *.* 时, 只对文件操作

FOF_SIMPLEPROGRESS 0x0100 // 简单进度条,意味者不显示文件名。

FOF_NOCONFIRMMKDIR 0x0200 // 建新目录时不需要用户确定

FOF_NOERRORUI 0x0400 // 不显示出错用户界面

FOF_NOCOPYSECURITYATTRIBS 0x0800 // 不复制 NT 文件的安全属性

FOF_NORECURSION 0x1000 // 不递归目录

返回值:

函数成功返回 0 ,失败返回非 0 。

例子:

1. 将 C:\Test.txt 拷贝到 D:\

SHFILEOPSTRUCT lpsh;

ZeroMemory(&lpsh,sizeof(lpsh));

lpsh.hwnd= HWND_DESKTOP;

lpsh.fFlags=FOF_NOCONFIRMATION|FOF_SIMPLEPROGRESS ;

lpsh.wFunc=FO_COPY; // FO_MOVE 则是移动

lpsh.pFrom= "C:\Test.txt";

lpsh.pTo = "D:\"

if( 0 != SHFileOperation(&lpsh))

{

AfxMessageBox("复制文件出错,请检查");

return ;

}

2. 删除 D:\Test.txt

SHFILEOPSTRUCT lpsh;

ZeroMemory(&lpsh,sizeof(lpsh));

lpsh.hwnd= HWND_DESKTOP;

lpsh.fFlags=FOF_NOCONFIRMATION|FOF_SIMPLEPROGRESS ;

lpsh.wFunc=FO_DELETE;

lpsh.pFrom= "D:\Test.txt";

if( 0 != SHFileOperation(&lpsh))

{

AfxMessageBox("删除文件出错,请检查");

return ;

}

3.重命名

SHFILEOPSTRUCT lpsh;

ZeroMemory(&lpsh,sizeof(lpsh));

lpsh.hwnd= HWND_DESKTOP;

lpsh.fFlags=FOF_NOCONFIRMATION|FOF_SIMPLEPROGRESS ;

lpsh.wFunc=FO_RENAME;

lpsh.pFrom= "D:\Test.txt";

lpsh.pTo = "D:\Test2.txt";

if( 0 != SHFileOperation(&lpsh))

{

AfxMessageBox("重命名文件出错!");

return ;

}

4.VB

Public Declare Function SHFileOperation Lib "shell32.dll" Alias "SHFileOperationA" (lpFileOp As SHFILEOPSTRUCT) As Long

Public Const FO_COPY = &H2

Public Const FOF_ALLOWUNDO = &H40

Public Sub ShellCopyFile(Source As String, Dest As String)

Dim result As Long

Dim fileop As SHFILEOPSTRUCT

With fileop

.hwnd = 0

.wFunc = FO_COPY

.pFrom = Source & vbNullChar & vbNullChar

.pTo = Dest & vbNullChar & vbNullChar

.fFlags = FOF_ALLOWUNDO

End With

result = SHFileOperation(fileop)

If result <> 0 Then

'Msgbox the error that occurred in the API.

MsgBox Err.LastDllError, vbCritical Or vbOKOnly

Else

If fileop.fAnyOperationsAborted <> 0 Then

MsgBox "Operation Failed", vbCritical Or vbOKOnly

End If

End If

End Sub
  1. 单开一个内存,清空,把pForm指向这里,把内容拷进去
  2. SHFILEOPSTRUCT Op;
  3. ZeroMemory(&Op, sizeof(Op));
  4. TCHAR ToBuf[MAX_PATH];
  5. TCHAR FromBuf[MAX_PATH];
  6. ZeroMemory(ToBuf, sizeof(ToBuf));
  7. ZeroMemory(FromBuf, sizeof(FromBuf));
  8. lstrcpy(FromBuf, strDeleteFile);
  9. Op.hwnd = NULL;
  10. Op.pFrom = FromBuf;
  11. Op.pTo = ToBuf;
  12. Op.fFlags = FOF_NOCONFIRMATION ¦ FOF_NOCONFIRMMKDIR ¦ FOF_NOERRORUI;
  13. Op.fAnyOperationsAborted = FALSE;
  14. Op.hNameMappings = NULL;
  15. Op.lpszProgressTitle = NULL;
  16. Op.wFunc = FO_DELETE;
  17. SHFileOperation(&Op);
  18. ===================
  19. vb.net
  20. Public Structure SHFILEOPSTRUCT
  21. Dim hwnd As IntPtr
  22. Dim wFunc As Integer
  23. Dim pFrom As String
  24. Dim pTo As String
  25. Dim fFlags As Short
  26. Dim fAnyOperationsAborted As Integer
  27. Dim hNameMappings As IntPtr
  28. Dim lpszProgressTitle As String
  29. End Structure
  30. Public Declare Function SHFileOperation Lib "shell32.dll" Alias "SHFileOperationA" (ByRef lpFileOp As SHFILEOPSTRUCT) As Integer
  31. ======================
  32. vb:
  33. Type SHFILEOPSTRUCT
  34. hWnd As Long
  35. wFunc As Long
  36. pFrom As String '必须用 pFrom & vbNullChar & vbNullChar
  37. pTo As String '同pFrom
  38. fFlags As Integer
  39. fAnyOperationsAborted As Boolean
  40. hNameMappings As Long
  41. lpszProgressTitle As String
  42. End Type
  43. Public Declare Function SHFileOperation Lib "shell32.dll" Alias "SHFileOperationA" (lpFileOp As SHFILEOPSTRUCT) As Long