服务器文件自动备份工具

网站经常需要定期备份文件,天天折腾累死人 ,索性写了个自动备份 的工具,让它运行在服务器上,每天凌晨自动将需要备份的数据打包成压缩文件并传到另外的服务器。

这是设计的草图

1、定时执行任务,用到开源框架Quartz.net
使用方法:
引用Quartz.dll

 IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
                scheduler.Start();
                IJobDetail job = JobBuilder.Create<HelloJob>()
                    .WithIdentity("job1", "group1")
                    .Build();

                var tr = TriggerBuilder.Create().WithCronSchedule(runtime).Build();

                scheduler.ScheduleJob(job, tr);

其中 runtime 变量是 定义执行的时间:

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

说明: 0 3 19 分别为 秒,分,时

其中的 HelloJob 是需要实现IJob接口的类,在其中写备份文件的一系列方法。

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

//…这里写实现的方法

    }

}

2、实现文件的备份
整个过程包括:文件复制、压缩文件、上传压缩文件到制定服务器、发送通知邮件

直接复制文件夹:

  static bool DirectoryCopy(string sourceDir, string targetDir)
        {
            bool back = false;
            if (Directory.Exists(sourceDir) && Directory.Exists(targetDir))
            {

                string sourceFolderName = sourceDir.Replace(Directory.GetParent(sourceDir).ToString(), "").Replace(Path.DirectorySeparatorChar.ToString(), "");

                if (sourceDir != targetDir + sourceFolderName)
                {
                    //要复制到的路径
                    string tagetPath = targetDir + Path.DirectorySeparatorChar.ToString() + sourceFolderName;
                    if (Directory.Exists(tagetPath))
                    {
                        Directory.Delete(tagetPath, true);
                    }

                    Directory.CreateDirectory(tagetPath);

                    //复制文件
                    string[] files = Directory.GetFiles(sourceDir);
                    for (int i = 0; i < files.Length; i++)
                    {
                        File.Copy(files[i], tagetPath + Path.DirectorySeparatorChar.ToString() + Path.GetFileName(files[i]));
                    }
                    //复制目录
                    string[] dires = Directory.GetDirectories(sourceDir);
                    for (int j = 0; j < dires.Length; j++)
                    {
                        DirectoryCopy(dires[j], tagetPath);
                    }

                    back = true;
                }


            }



            return back;





        }

对复制产生的新文件目录进行打包(不能对原使用中的文件进行打包操作,因为被占用的资源在打包时会出错)

打包技术采用 SharpZipLib组件

打包压缩文件方法类:
引用 ICSharpCode.SharpZipLib.dll

    /// <summary>
    /// ZipFloClass 的摘要说明
    /// </summary>
    public class ZipFloClass
    {
        public void ZipFile(string strFile, string strZip)
        {
            if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar)
                strFile += Path.DirectorySeparatorChar;
            ZipOutputStream s = new ZipOutputStream(File.Create(strZip));
            s.SetLevel(6); // 0 - store only to 9 - means best compression
            zip(strFile, s, strFile);
            s.Finish();
            s.Close();
        }


        private void zip(string strFile, ZipOutputStream s, string staticFile)
        {
            if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar) strFile += Path.DirectorySeparatorChar;
            Crc32 crc = new Crc32();
            string[] filenames = Directory.GetFileSystemEntries(strFile);
            foreach (string file in filenames)
            {

                if (Directory.Exists(file))
                {
                    zip(file, s, staticFile);
                }

                else // 否则直接压缩文件
                {
                    //打开压缩文件
                    FileStream fs = File.OpenRead(file);

                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    string tempfile = file.Substring(staticFile.LastIndexOf("\\") + 1);
                    ZipEntry entry = new ZipEntry(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);
                }
            }
        }

    }

外层调用上面类里面方法进行压缩文件

        static bool yasuoFile(string yasuoPath, string savePath, string name)
        {

            bool back = false;
            string[] FileProperties = new string[2];

            FileProperties[0] = yasuoPath;//待压缩文件目录
            FileProperties[1] = savePath + name+ ".zip";  //压缩后的目标文件
            ZipFloClass Zc = new ZipFloClass();

            Zc.ZipFile(FileProperties[0], FileProperties[1]);

            back = true;

            return back;
        }

上传文件

上传文件客户端:

        /// <summary>
        /// 上传文件 到 WebService接口
        /// </summary>
        /// <param name="path"></param>
        static string uploadfile(string path)
        {
            try { 

            webservice.WebServiceSoapClient upload = new webservice.WebServiceSoapClient();

            byte[] b = GetBytesByPath(path);
            string name = Path.GetFileName(path);
            string back = upload.SaveFile(b, name);
            return back;

            }
            catch(Exception ex){
                return "上传数据失败!"+ex.ToString();
            }

        }

文件接收端WebService:

        [WebMethod]
        public string SaveFile(byte [] file,string filename)
        {
            string back = "";
            string FileDir =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;
        }

注意:配置文件中配置上传文件大小

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

发送邮件方法:

        static bool SendEmailAction(string Subject, string ToWho, string SendContent, string mailServer, int mailSerPort, string myAccount, string myPwd)
        {
            try
            {

                MailMessage myMail = new MailMessage();
                myMail.From = new MailAddress(myAccount);
                myMail.To.Add(new MailAddress(ToWho));
                myMail.Subject = Subject;
                myMail.SubjectEncoding = Encoding.UTF8;
                myMail.Body = SendContent;
                myMail.BodyEncoding = Encoding.UTF8;
                myMail.IsBodyHtml = true;
                SmtpClient smtp = new SmtpClient();
                smtp.Host = mailServer;
                smtp.Port = mailSerPort;

                //smtp.UseDefaultCredentials = true;
                smtp.Credentials = new NetworkCredential(myAccount, myPwd);
                smtp.EnableSsl = true; //要求SSL连接
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network; //Gmail的发送方式是通过网络的方式,需要指定
                smtp.Send(myMail);
            }
            catch (Exception ex)
            {
                return false;
            }

            return true;
        }

至此,关键的代码完成,拼凑去吧!!需要备份工具的可以联系我!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值