C # Implementation of File operations encapsulation class full instance code sharing

Source: Internet
Author: User
This article mainly introduces the C # implementation of the file operation encapsulation class, combined with a complete instance of the C # Packaging file analysis of the deletion, movement, replication, renaming and other operations related implementation skills, the need for friends can refer to the next

This example describes the file operation encapsulation class implemented by C #. Share to everyone for your reference, as follows:

Recently found in the group share there is a C # file Operation Encapsulation class, which is done by invoking the Windows API to manipulate the deletion, movement, copying, and renaming of files. Download down a try, found really good, special in this record, in case of loss!

The file Operation class code is as follows:


Using system;using system.runtime.interopservices;using system.io;namespace lxfile{//<summary>///File Operations agent, This class provides a Windows-like file manipulation experience///</summary> public class Fileoperateproxy {#region "internal type definition" private struct shfile     opstruct {public INTPTR hwnd;     Parent window handle public wfunc wfunc;    The action to execute public string pfrom;     The source file path, which can be multiple files, ends with the sign "" "to end public string pTo;       The destination path, which can be either a path or a file name public fileop_flags fflags;   Flags, additional options public bool fanyoperationsaborted;      Whether the public IntPtr hnamemappings can be interrupted;    File mapping name, you can use the public string lpszprogresstitle in other Shell functions;    Specifies the caption of the dialog box only when Fof_simpleprogress. } private enum Wfunc {fo_move = 0x0001,//move file Fo_copy = 0x0002,//Copy file Fo_delete = 0x0003,//delete file , just use pfrom fo_rename = 0x0004//File Rename} Private enum Fileop_flags {fof_multidestfiles = 0x0001,//pto     Multiple target files are specified instead of a single directory fof_confirmmouse = 0x0002, fof_silent = 0x0044, Do not display a progress dialog box Fof_renameoncollision = 0x0008,//When encountering a conflicting name, automatically assign a prefix fof_noconfirmation = 0x10,//Do not display a prompt to the user       Fof_wantmappinghandle = 0x0020,//Fill hnamemappings field, must use Shfreenamemappings release Fof_allowundo = 0x40,//Allow Undo      Fof_filesonly = 0x0080,//when using *. *, only the file operation fof_simpleprogress = 0x0100,//simple progress bar, meaning that the file name is not displayed.  Fof_noconfirmmkdir = 0x0200,///Jianxin directory does not require user identification Fof_noerrorui = 0x0400,//Error user interface is not displayed Fof_nocopysecurityattribs = 0x0800,//Do not copy the security properties of NT files fof_norecursion = 0x1000//non-recursive directory} #endregion "internal type definition" #region "DllImport    "[DllImport (" Shell32.dll ")] private static extern int SHFileOperation (ref shfileopstruct LPFILEOP);    #endregion "DllImport" #region "Delete file operations"///<summary>//delete individual files. </summary>//<param name= "filename" > Deleted filename </param>//<param name= "Torecycle" > indicates that the file is placed into the Recycle Bin or permanently deleted, true-into the Recycle Bin, false-permanently deleted </param>///<param Name= "ShowDialog" > Indicates whether the confirmation dialog box is displayed, true-displays the Confirm Delete dialog box, false-does not display the Confirm Delete dialog </param>///<param Name= "ShowProgress" > Indicates whether the progress dialog box is displayed, true-display, false-not displayed. This parameter is valid when specifying a permanently deleted file </param>//<param name= "errormsg" > Feedback error message string </param>//<returns> operation execution Result ID , delete file successfully returned 0, otherwise, return error code </returns> public static int DeleteFile (string fileName, bool torecycle, BOOL ShowDialog, Boo        L ShowProgress, ref string errormsg) {try {string fName = Getfullname (fileName);      Return Todelete (FName, Torecycle, ShowDialog, showprogress, ref errormsg); } catch (Exception ex) {errormsg = ex.        Message;      return-200;    }}///<summary> Delete a set of files. </summary>//<param name= "FileNames" > string array representing a set of filenames </param>//<param name= "Torecycle" ; Indicates whether to put the file in the Recycle Bin or permanently delete, true-into the Recycle Bin, false-permanently delete </param>///<param Name= "ShowDialog" > Indicates if confirmation dialog box is displayed, true-Display Confirm Delete dialog box, false-do not display confirmation Delete dialog </param>///<param name= "shOwprogress "> Indicates whether the progress dialog box is displayed, true-display, false-not displayed. This parameter is valid when specifying a permanently deleted file </param>//<param name= "errormsg" > Feedback error message string </param>//<returns> operation execution Result ID  , delete the file successfully returned 0, otherwise, return error code </returns> public static int deletefiles (string[] fileNames, BOOL torecycle, BOOL ShowDialog,        bool ShowProgress, ref string errormsg) {try {string fName = "";   foreach (String str in fileNames) {fName + = Getfullname (str) + "+";      Component file group string} return Todelete (FName, Torecycle, ShowDialog, showprogress, ref errormsg); } catch (Exception ex) {errormsg = ex.        Message;      return-200; }} #endregion "Delete file operations" #region "Move File Operations"///<summary>///////////</summary> move a file to the specified path//// /<param name= "sourceFileName" > file name to move </param>//<param name= "DestinationPath" > moved to the destination path </ param>//<param name= "ShowDialog" > Indicates whether confirmation dialog box is displayed, true-Display Confirmation dialog, false-does not display confirmation dialog box </param>//<param name= "ShowProgress" > Indicates whether the progress dialog box is displayed </param>//<param name= "Autorename" > indicates that when the file name is repeated, it is No automatically adds suffix to new files </param>//<param name= "errormsg" > Feedback error message string </param>///<returns> Returns whether the move operation was successful Identity, successful return 0, failure return error code </returns> public static int MoveFile (string sourcefilename, String destinationpath, bool Showdi Alog, BOOL showprogress, bool Autorename, ref string errormsg) {try {string sfname = Getfullname (sou        Rcefilename);        String dfname = Getfullname (DestinationPath);      Return Tomoveorcopy (Wfunc.fo_move, Sfname, Dfname, ShowDialog, showprogress, Autorename, ref errormsg); } catch (Exception ex) {errormsg = ex.        Message;      return-200; }}////<summary>///To move a set of files under the specified path///</summary>//<param name= "Sourcefilenames" > Array of file names </param>//<param name= "DestinationPath" > moved to the destination path </param>//<param name= "ShowdialoG "> Indicates whether confirmation dialog is displayed, true-displays confirmation dialog, false-does not display confirmation dialog box </param>//<param name=" ShowProgress "> Indicates whether the progress dialog box is displayed </ param>//<param name= "Autorename" > indicates whether the new file is automatically appended with the suffix </param>//<param name= "ErrorMsg" when the file name is duplicated > String of feedback error message </param>/////<returns> Returns the successful identification of the move operation, returns 0 successfully, failure return error code, 200: Other exceptions </returns> public static int MoveFiles (string[] sourcefilenames, string destinationpath, bool ShowDialog, BOOL showprogress, bool Autorename, ref s        Tring errormsg) {try {string sfname = "";  foreach (String str in sourcefilenames) {sfname + = Getfullname (str) + "+";        Component file Group String} string dfname = Getfullname (DestinationPath);      Return Tomoveorcopy (Wfunc.fo_move, Sfname, Dfname, ShowDialog, showprogress, Autorename, ref errormsg); } catch (Exception ex) {errormsg = ex.        Message;      return-200;   }} #endregion "Move file Operations" #region "Copy file Operations"//<summary> Copy a file to the specified file name or path///</summary>//<param name= "sourceFileName" > file name to copy </param>//<p Aram Name= "Destinationfilename" > copied to the destination filename or path </param>///<param Name= "ShowDialog" > Indicates whether a confirmation dialog box is displayed, true-Display Confirmation dialog box, false-do not display confirmation dialog </param>///<param Name= "ShowProgress" > Indicates whether the progress dialog box is displayed </param>//&LT;PA Ram Name= "Autorename" > indicates whether the new file is automatically appended with the suffix name </param>//<returns> Returns the successful identity of the move operation, returns 0 successfully, fails to return an error code,- 200: Represents additional exception </returns> public static int CopyFile (string sourcefilename, String destinationfilename, bool Showdialo G, BOOL showprogress, bool Autorename, ref string errormsg) {try {string sfname = Getfullname (source        FileName);        String dfname = Getfullname (Destinationfilename);      Return Tomoveorcopy (Wfunc.fo_copy, Sfname, Dfname, ShowDialog, showprogress, Autorename, ref errormsg); } catch (Exception ex) {errormsg = ex.        Message;      return-200; }    }    ///<summary>///Copy a set of files to the specified path///</summary>//<param name= "Sourcefilenames" > array of file names to copy </par am>//<param name= "DestinationPath" > copied to the Destination path </param>//<param name= "ShowDialog" > Indicates whether a confirmation dialog box is displayed , true-displays confirmation dialog, false-does not display confirmation dialog </param>///<param Name= "ShowProgress" > Indicates whether Progress dialog box is displayed </param>//<p Aram Name= "Autorename" > indicates whether the new file is automatically appended with the suffix name </param>//<returns> Returns the successful identity of the move operation, returns 0 successfully, fails to return an error code,- 200: Represents additional exceptions </returns> public static int CopyFiles (string[] sourcefilenames, string destinationpath, bool Showdialo        G, BOOL showprogress, bool Autorename, ref string errormsg) {try {string sfname = "";   foreach (String str in sourcefilenames) {sfname + = Getfullname (str) + "+";        Component file Group String} string dfname = Getfullname (DestinationPath);    Return Tomoveorcopy (Wfunc.fo_copy, Sfname, Dfname, ShowDialog, showprogress, Autorename, ref errormsg);  } catch (Exception ex) {errormsg = ex.        Message;      return-200; }} #endregion "Copy file operation" #region "Rename file"///<summary>///rename a file to a new name, it is recommended that you use a more convenient microsoft.visualbasic. Filesystem.rename (); Replace this method//</summary>//<param name= "sourceFileName" > file name to be copied </param>/// Lt;param name= "Destinationfilename" > copied to the destination filename or path </param>///<param Name= "ShowDialog" > Indicates whether a confirmation dialog box is displayed, true-Display Confirmation dialog box, false-do not display confirmation dialog </param>////<returns> Returns whether the move operation succeeded in identifying, successfully returned 0, failed to return error code, 200: Represents a different exception </ returns> [Obsolete ("Recommended use of Microsoft.VisualBasic.FileSystem.ReName () method")] public static int RenameFile (String sourc Efilename, String destinationfilename, bool ShowDialog, ref string errormsg) {try {shfileopstruct LP        Fileop = new Shfileopstruct ();        Lpfileop.wfunc = Wfunc.fo_rename;     Lpfileop.pfrom = Getfullname (sourcefilename) + "\0\0"; Ends the file name with the end character "\0\0" Lpfileop.pto = Getfullname (desTinationfilename) + "\0\0"; Lpfileop.fflags = Fileop_flags.        Fof_noerrorui; if (!showdialog) lpfileop.fflags |= fileop_flags.   Fof_noconfirmation;        Set do not show prompt dialog lpfileop.fanyoperationsaborted = true;        int n = shfileoperation (ref lpfileop);        if (n = = 0) return 0;        string tmp = GetErrorString (n); ErrorMsg = string.        Format ("{0} ({1})", TMP, sourceFileName);      return n; } catch (Exception ex) {errormsg = ex.        Message;      return-200; }}///<summary>///Microsoft.VisualBasic.FileSystem.ReName () method for//</summary>//&LT;PA Ram Name= "FilePath" ></param>///<param name= "NewFileName" ></param> public static void Renamefi        Le (String filePath, String newfilename) {try {string extensname = Path.getextension (FilePath);        String newName = NewFileName + extensname; Microsoft.VisualBasic.FileIO.FileSystem.RenameFile (filEpath, NewName);      } catch (Exception ex) {throw ex; }} #endregion "Rename file"///<summary>//delete single or multiple files///</summary>//<param name= "Filena Me "> deleted file name, if it is multiple files, the file name is separated by the string Terminator ' \ S ' </param>//<param name=" Torecycle "> indicates whether the file is placed in the Recycle Bin or permanently deleted, true-into Recycle Bin, false-permanently delete </param>///<param Name= "ShowDialog" > Indicates whether confirmation dialog is displayed, true-Show confirm Delete dialog box, False-does not display the Confirm Delete dialog box </param>//<param name= "ShowProgress" > Indicates whether the progress dialog box is displayed, true-is displayed, false-is not displayed. This parameter is valid when specifying a permanently deleted file </param>//<param name= "errormsg" > Feedback error message string </param>//<returns> operation execution Result ID  , delete file successfully returned 0, otherwise, return error code </returns> private static int Todelete (string fileName, bool torecycle, BOOL ShowDialog, BOOL      ShowProgress, ref string errormsg) {shfileopstruct lpfileop = new Shfileopstruct ();      Lpfileop.wfunc = Wfunc.fo_delete;    Lpfileop.pfrom = FileName + "n"; Ends the file name with the trailing character "lpfileop.fflags" = fileop_flags. Fof_noerrorui;     if (torecycle) lpfileop.fflags |= fileop_flags. Fof_allowundo; Set Delete to Recycle Bin if (!showdialog) lpfileop.fflags |= fileop_flags.   Fof_noconfirmation; Setting does not display the prompt dialog box if (!showprogress) lpfileop.fflags |= fileop_flags.   Fof_silent;      Set the Do not show progress dialog box lpfileop.fanyoperationsaborted = true;      int n = shfileoperation (ref lpfileop);      if (n = = 0) return 0;      string tmp = GetErrorString (n); The. av file was deleted normally but also prompted 402 error, do not know why.      Shielding it. if (Filename.tolower ().      EndsWith (". av") && n.tostring ("X") = = "402")) return 0; ErrorMsg = string.      Format ("{0} ({1})", TMP, FileName);    return n; }///<summary>///To move or copy one or more files to the specified path///</summary>//<param name= "flag" > Operation type, whether it is a move or copy operation Make </param>//<param name= "sourceFileName" > the name of the file to be moved or copied, and if it is multiple files, the file name is separated by a string ending with ' \ s ' </param>//< param name= "Destinationfilename" > moved to the destination </param>//<param name= "ShowDialog" > Indicates whether a confirmation dialog box is displayed,true-Display Confirmation dialog box, false-do not display confirmation dialog </param>///<param Name= "ShowProgress" > Indicates whether the progress dialog box is displayed </param>//&LT;PA Ram Name= "Autorename" > indicates whether the new file is automatically appended with the suffix </param>//<param name= "errormsg" > Feedback error message string </when the file name repeats param>//<returns> Returns whether the move operation succeeded in identifying, returned 0 successfully, failed to return error code </returns> private static int tomoveorcopy (WFUNC flag , string sourceFileName, String destinationfilename, bool ShowDialog, BOOL showprogress, bool Autorename, ref string E      rrormsg) {shfileopstruct lpfileop = new Shfileopstruct ();      Lpfileop.wfunc = Flag;     Lpfileop.pfrom = sourceFileName + "+";      End the file name with the end character "\0\0" Lpfileop.pto = Destinationfilename + "\0\0"; Lpfileop.fflags = Fileop_flags.      Fof_noerrorui; Lpfileop.fflags |= fileop_flags. Fof_noconfirmmkdir; Specifies that the path if (!showdialog) lpfileop.fflags |= Fileop_flags can be created directly when needed.   Fof_noconfirmation; Setting does not display the prompt dialog box if (!showprogress) lpfileop.fflags |= fileop_flags.   Fof_silent; Setting does not show progressdialog box if (autorename) lpfileop.fflags |= fileop_flags. Fof_renameoncollision;      Automatically add name suffix to renamed file lpfileop.fanyoperationsaborted = true;      int n = shfileoperation (ref lpfileop);      if (n = = 0) return 0;      string tmp = GetErrorString (n); ErrorMsg = string.      Format ("{0} ({1})", TMP, sourceFileName);    return n;    }///<summary>//Get the full name of a file///</summary>//<param name= "filename" > file name </param> <returns> returns the full path name of the generated file </returns> private static string Getfullname (String fileName) {FileInfo      fi = new FileInfo (fileName); return FI.    FullName; }//<summary>///Interpretation error code///</summary>//<param name= "n" > Code number </param>//<r Eturns> returns a literal description of the error code </returns> private static string geterrorstring (int n) {if (n = = 0) return string .      Empty; Switch (n) {case 2:return ' system cannot find the file specified.        "; Case 7:return "StorageThe control block is destroyed. Do you want to select the "Cancel" action?        "; Case 113:return "File already exists!        "; Case 115:return "Rename the file operation, the original file and the destination file must have the same path name. Relative paths cannot be used.        ";        Case 117:return "I/O control error";        Case 123:return "specified duplicate filename";        Case 116:return "The source was a root directory, which cannot be moved or renamed.";        Case 118:return, "Security settings denied access to the source.";        Case 124:return "The path in the source or destination or both is invalid.";        Case 65536:return "A unspecified error occurred on the destination.";        Case 1026:return "is attempting to move or copy a nonexistent file."; Case 1223:return "Operation was canceled!        ";      Default:return "Unrecognized error code:" + N; }    }  }}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.