C # Backup, restore, copy remote folders

Source: Internet
Author: User
Tags file copy

have been very busy recently, very sorry for a long time did not write a blog. Recently encountered some work of copying remote files, such as our published Web site, development provides a ZIP compression package, we need to upload to remote server A, and then in the deployment (file copy) to Remote Environment B and C,ABC are in a LAN.

First we need a tool class to convert the file path, local address and remote address conversion such as 192.168.0.1 on the D:\test conversion to \\192.168.0.1\D$\test, file path splicing,

  Public classPathutil { Public Static stringGetremotepath (stringIpstringLocalPath) {            if(!localpath.contains (":"))            {                Throw NewException ($"{LocalPath} path must be full path and local path"); } LocalPath= Localpath.replace (":","$"); return$@"\\{ip}\{localpath}"; }         Public Static stringGetlocapath (stringRemotePath) {            intindex = Remotepath.indexof ("$"); if(Index <1)            {                Throw NewException ($"{RemotePath} path must contain disk information"); }            stringtemp = remotepath.substring (Index-1); Temp= Temp. Replace ("$",":"); returntemp; }         Public Static stringCombine (stringPath1,stringpath2) {path1=path1.            Trim (); Path2=path2.            Trim (); if(path1. EndsWith ("\\") && path2. StartsWith ("\\"))            {                stringRET = (path1 + path2). Replace ("\\",""); returnret; }            Else if(!path1. EndsWith ("\\") &&!path2. StartsWith ("\\"))            {                returnPath1 +"\\"+path2; }            //if (path1. EndsWith ("\ \") &&!path2.            StartsWith ("\ \")) | | //(!path1. EndsWith ("\ \") && path2. StartsWith ("\ \"))) {}            returnPath1 +path2; }    }

Back up the Remote Directory folder ( first backup remote a directory to local temporary file zip-> copy to remote b-> Delete local temporary file zip)

Restore remote files (deployment release package) ( remote files extracted to local temp directory, copy to destination server, delete local temp directory )

Folder to copy is relatively simple, recursive call file copy is okay, such as \\192.168.0.1\D$\test Copy to \\192.168.0.2\D$\test (it is recommended to delete the existing file in the copy).

The relevant code is as follows:

  #regionFile Operations Section/// <summary>        ///Copy the files in a directory under the target directory/// </summary>        /// <param name= "Sourcefolder" >Source Directory</param>        /// <param name= "Targerfolder" >Target directory</param>        /// <param name= "Removeprefix" >Remove file name part path</param>         Public voidCopyFiles (stringSourcefolder,stringTargerfolder,stringRemoveprefix ="")        {            if(string. IsNullOrEmpty (Removeprefix)) {Removeprefix=Sourcefolder; }            if(!directory.exists (Targerfolder))            {directory.createdirectory (Targerfolder); } DirectoryInfo Directory=NewDirectoryInfo (Sourcefolder); //get the file under the directoryfileinfo[] Files =directory.            GetFiles (); foreach(FileInfo Iteminchfiles) {                if(item. Name = ="Thumbs.db")                {                    Continue; }                stringTempPath = Item. Fullname.replace (Removeprefix,string.                Empty); TempPath= Targerfolder +TempPath; FileInfo FileInfo=NewFileInfo (TempPath); if(!fileInfo.Directory.Exists) {fileInfo.Directory.Create ();                } file.delete (TempPath); Item. CopyTo (TempPath,true); }            //get subdirectories under directoryDirectoryinfo[] Directors =directory.            GetDirectories (); foreach(varIteminchdirectors) {CopyFiles (item.            FullName, Targerfolder, Removeprefix); }        }        /// <summary>        ///back up the remote folder as a zip file/// </summary>        /// <param name= "Sourcefolder" >Backup Directory</param>        /// <param name= "Targertfile" >target file</param>        /// <returns></returns>         Public BOOLBackzip (stringSourcefolder,stringtargertfile) {            stringTempFileName = Pathutil.combine (Path.gettemppath (), Guid.NewGuid (). ToString () +". zip"); BOOLRET =false; Try{zipfile.createfromdirectory (Sourcefolder, TempFileName, Compressionlevel.optimal,false); varParentdirect = (NewFileInfo (Targertfile)).                Directory; if(!parentdirect.exists) {parentdirect.create (); } file.copy (TempFileName, Targertfile,true); RET=true; }            Catch(Exception ex) {Throw NewException ($"backup directory {Sourcefolder} error {ex. Message}"); }            finally            {                if(File.exists (tempfilename)) {file.delete (tempfilename); }            }            returnret; }        /// <summary>        ///To restore a remote file to a remote directory/// </summary>        /// <param name= "SourceFile" >Remote Files</param>        /// <param name= "TargetFolder" >Remote Directory</param>        /// <returns></returns>         Public BOOLRestorezip (stringSourceFile,stringTargetFolder) {            stringTempfoldername =Pathutil.combine (Path.gettemppath (), Guid.NewGuid ().            ToString ()); BOOLRET =false; Try            {                using(Ziparchive Readzip =Zipfile.openread (sourcefile))                {readzip.extracttodirectory (tempfoldername); }                stringCopyFolder =Tempfoldername; //if (! Directory.GetFiles (CopyFolder). Any () && directory.getdirectories (CopyFolder). Length = = 1)//{                //CopyFolder = directory.getdirectories (CopyFolder) [0]; //}CopyFiles (CopyFolder, TargetFolder, CopyFolder); RET=true; }            Catch(Exception ex) {Throw NewException ($"Error in publishing file {SourceFile} to {TargetFolder} {ex. Message}"); }            finally            {                if(Directory.Exists (tempfoldername)) {Directory.delete (Tempfoldername,true); }            }            returnret; }        #endregion

C # Backup, restore, copy remote folders

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.