Server File Automatic Backup tool

Source: Internet
Author: User
Tags crc32 mailmessage smtpclient ssl connection

Site often need to regularly back up files, daily toss tired people, simply write an automatic backup tool, let it run on the server, every morning, the need to automatically pack the backup data into a compressed file and upload to another server.

1, scheduled to carry out the task, using the open source framework Quartz.net
How to use:
Reference Quartz.dll

 IScheduler scheduler = Stdschedulerfactory ()  Scheduler ()  Ijobdetail job = Jobbuilder <HelloJob> ()  ( "Job1" ,  "group1" )  ()  var tr = Triggerbuilder ()  (runtime)  ()  Scheduler (Job, tr) ;  

Where the runtime variable is the time to define execution:

<add key="runtime" value="0 3 19 * * ?"/>

Description: 0 3 19 seconds, minutes, respectively, time

One of the hellojob is the class that needs to implement the Ijob interface, in which the backup file is written in a series of ways.

class HelloJob : IJob{    public void Execute(IJobExecutionContext context)    {

... Here's how to write the implementation

    }

}

2, the implementation of file backup
The entire process includes: file copying, compressing files, uploading compressed files to the development server, sending notification messages

To copy a folder directly:

  Static BOOLDirectorycopy (stringSourceDir,stringTargetDir) {BOOLback =false;if(Directory.Exists (SourceDir) && directory.exists (TargetDir)) {stringSourcefoldername = Sourcedir.replace (Directory.getparent (SourceDir). ToString (),""). Replace (Path.DirectorySeparatorChar.ToString (),"");if(SourceDir! = TargetDir + sourcefoldername) {//path to copy to                    stringTagetpath = TargetDir + Path.DirectorySeparatorChar.ToString () + sourcefoldername;if(Directory.Exists (Tagetpath)) {Directory.delete (Tagetpath,true); } directory.createdirectory (Tagetpath);//Copy files                    string[] files = Directory.GetFiles (SourceDir); for(inti =0; I < files. Length; i++) {file.copy (files[i], Tagetpath + Path.DirectorySeparatorChar.ToString () +                    Path.getfilename (Files[i])); }//Copy directory                    string[] Dires = Directory.getdirectories (SourceDir); for(intj =0; J < Dires. Length;                    J + +) {directorycopy (dires[j], tagetpath); } back =true; }            }returnBack }

Package The new file directory generated by the copy (cannot package the original files in use, because the consumed resources will be faulted when packaged)

Packaging Technology with SharpZipLib components

Package compressed file Method class:
Reference ICSharpCode.SharpZipLib.dll

    //   <summary>     ///   zipfloclass Summary description    //   </summary>      Public classZipfloclass { Public void ZipFile(stringStrfile,stringStrzip) {if(Strfile[strfile.length-1] = Path.directoryseparatorchar) strfile + = Path.directoryseparatorchar; Zipoutputstream s =NewZipoutputstream (File.create (strzip)); S.setlevel (6);//0-store-9-means Best CompressionZip (strfile, S, strfile);            S.finish ();        S.close (); }Private void Zip(stringStrfile, Zipoutputstream S,stringStaticfile) {if(Strfile[strfile.length-1] = Path.directoryseparatorchar) strfile + = Path.directoryseparatorchar; Crc32 CRC =NewCRC32 ();string[] filenames = directory.getfilesystementries (strfile);foreach(stringFileinchFilenames) {if(directory.exists (file))                {Zip (file, S, staticfile); }Else //Otherwise directly compress files{//Open compressed FilesFileStream fs = File.openread (File);byte[] buffer =New byte[FS.                    Length]; Fs. Read (Buffer,0, buffer. Length);stringTempfile = file. Substring (Staticfile.lastindexof ("\\") +1); ZipEntry entry =NewZipEntry (Tempfile); Entry.                    DateTime = DateTime.Now; Entry. Size = fs.                    Length; Fs.                    Close (); Crc.                    Reset (); Crc.                    Update (buffer); Entry. CRC = CRC.                    Value;                    S.putnextentry (entry); S.write (Buffer,0, buffer.                Length); }            }        }    }

The outer layer calls the above class inside the method to compress the file

        Static BOOLYasuofile (stringYasuopath,stringSavepath,stringName) {BOOLback =false;string[] FileProperties =New string[2]; fileproperties[0] = Yasuopath;//file directory to be compressedfileproperties[1] = Savepath + name+". zip";//Compressed target fileZipfloclass Zc =NewZipfloclass (); Zc.zipfile (fileproperties[0], fileproperties[1]); back =true;returnBack }

Uploading files

Upload file client:

        //   <summary>         ///   upload files to WebService interface        //   </summary>         //   <param name= "path" ></param>         Static stringUploadFile (stringPath) {Try{WebService. Webservicesoapclient upload =NewWebService. Webservicesoapclient ();byte[] B = getbytesbypath (path);stringName = Path.getfilename (Path);stringback = Upload. SaveFile (b, name);returnBack }Catch(Exception ex) {return "failed to upload data!" "+ex.            ToString (); }        }

File Receive end WebService:

[WebMethod] PublicstringSaveFile (Byte []file,stringFileName) {string  Back="";stringFiledir =server.mappath (system.configuration.configurationmanager.appsettings["Filedir"]) + filename;Try{FileStream fs = new FileStream (filedir,filemode.openorcreate,fileaccess.write); Fs. Write (file,0,file.                Length); Fs. Close (); Back="1"; } catch (Exception ex) { Back= ex.            ToString (); }return  Back; }

Note: Configure the upload file size in the configuration file

<httpRuntime executionTimeout="300" maxRequestLength="40960" useFullyQualifiedRedirectUrl="false"/>

Send Message method:

        Static BOOLSendemailaction (stringSubject,stringTowho,stringSendcontent,stringMailServer,intMailserport,stringMyAccount,stringMYPWD) {Try{MailMessage MyMail =NewMailMessage (); Mymail.from =NewMailAddress (MyAccount); MYMAIL.TO.ADD (NewMailAddress (towho));                Mymail.subject = Subject;                mymail.subjectencoding = Encoding.UTF8;                Mymail.body = sendcontent;                mymail.bodyencoding = Encoding.UTF8; mymail.isbodyhtml =true; SmtpClient SMTP =NewSmtpClient (); Smtp.                Host = mailserver; Smtp. Port = Mailserport;//SMTP. useDefaultCredentials = true;Smtp. Credentials =NewNetworkCredential (MyAccount, mypwd); Smtp. Enablessl =true;//Require SSL connectionSmtp. Deliverymethod = Smtpdeliverymethod.network;The//gmail is sent over the network by the way it needs to be specifiedSmtp.            Send (MyMail); }Catch(Exception ex) {return false; }return true; }

At this point, the key code is done, piece it together!! Need Backup tool can contact me!

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Server File Automatic Backup tool

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.