SHFileOperation方法拷貝文件


 

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM