public enum FileOp
{
Move = 0x0001,
Copy = 0x0002,
Delete = 0x0003,
Rename = 0x0004
}
[Flags]
public enum FileOpFlags
{
MultiDestFiles = 0x0001,
ConfirmMouse = 0x0002,
Silent = 0x0004,
RenameCollision = 0x0008,
NoConfirmation = 0x0010,
WantMappingHandle = 0x0020,
AllowUndo = 0x0040,
FilesOnly = 0x0080,
SimpleProgress = 0x0100,
NoConfirmMkDir = 0x0200,
NoErrorUI = 0x0400,
NoCopySecurityAttributes = 0x0800,
NoRecursion = 0x1000,
NoConnectedElements = 0x2000,
WantNukeWarning = 0x4000,
NoRecursiveReparse = 0x8000
}
#endregion
#region Structure
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 1)]
public struct SHFILEOPSTRUCT
{
public IntPtr hwnd;
[MarshalAs(UnmanagedType.U4)]
public int wFunc;
public string pFrom;
public string pTo;
public short fFlags;
[MarshalAs(UnmanagedType.Bool)]
public bool fAnyOperationsAborted;
public IntPtr hNameMappings;
public string lpszProgressTitle;
}
#endregion
Import a shell method to copy file from one location to another,delete file,copy file and rename files and folders.
[DllImport("shell32.dll", CharSet = CharSet.Auto)]
public static extern int SHFileOperation(ref SHFILEOPSTRUCT FileOp);
Import a shell method to create a new directory.
[DllImport("shell32.dll")]
public static extern int SHCreateDirectoryEx(IntPtr hwnd, string pszPath, IntPtr psa);
To create a new folder :
private const string NULL_STRING = "\0";
newFolderPath is the path where you want to create your directory.
SHCreateDirectoryEx(this.Handle, newFolderPath + NULL_STRING, IntPtr.Zero);
To do all the file operation like move , copy ,delete and rename :-
public bool FileOperation(string sourceFileName, string destinationFileName, FileOp fileOp)
{
bool success = true;
try
{
SHFILEOPSTRUCT shf = new SHFILEOPSTRUCT();
shf.wFunc = (int)fileOp;
shf.fFlags = (short)FileOpFlags.AllowUndo | (short)FileOpFlags.NoConfirmation;
if(!string.IsNullOrEmpty(sourceFileName))
{
shf.pFrom = sourceFileName + NULL_STRING;
}
if(!string.IsNullOrEmpty(destinationFileName))
{
shf.pTo = destinationFileName + NULL_STRING;
}
int result = SHFileOperation(ref shf);
if (result != 0)
{
success = false;
}
}
catch (Exception exception)
{
MessageBox.Show(exception.Message, Application.ProductName, MessageBoxButtons.OK);
}
return success;
}
How to call this method :-
To Delete the file or folder.
FileOperation(newFolderPath, string.Empty, FileOp.Delete);
To Copy the File or Folder.
FileOperation(sourcePath, destinationPath, FileOp.Move);
To Rename the file or Folder.
FileOperation(sourcePath, destinationPath, FileOp.Rename);
0 comments:
Post a Comment