예제 #1
0
        /// <summary>
        /// http下载文件
        /// </summary>
        /// <param name="url">下载文件地址</param>
        /// <param name="file">文件存放地址,包含文件名</param>
        /// <param name="progress">回调进度</param>
        /// <returns></returns>
        public static bool Download(string url, string file, ProgressDelegate.ProgressHandler progress = null, object sender = null)
        {
            try
            {
                string path = Path.GetDirectoryName(file);
                DirTool.Create(path);                                                //创建文件目录

                string tempFile = DirTool.Combine(path, GuidTool.Short() + ".temp"); //临时文件
                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);                           //存在则删除
                }
                FileStream fs = new FileStream(tempFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                // 设置参数
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                //发送请求并获取相应回应数据
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                Stream responseStream = response.GetResponseStream();
                //创建本地文件写入流
                //Stream stream = new FileStream(tempFile, FileMode.Create);
                byte[] buffer = new byte[100 * 1024];
                int    readCount = 0;
                long   filesize = response.ContentLength, current = 0;
                while ((readCount = responseStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    fs.Write(buffer, 0, readCount);
                    current += readCount;
                    if (filesize <= 0 || filesize < current)
                    {
                        if (current > 0)
                        {
                            filesize = current;
                        }
                        else
                        {
                            filesize = 1;
                        }
                    }
                    progress?.Invoke(sender, new ProgressEventArgs(current, filesize));
                }
                //stream.Close();
                fs.Close();
                responseStream.Close();
                File.Delete(file);         //删除原始文件
                File.Move(tempFile, file); //下载的临时文件重命名
                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
예제 #2
0
        public static bool Exist(string file, string path, Pictures picture)
        {
            string normal   = DirTool.Combine(DirTool.Combine(path, "_data", "normal", $"{picture.Model}", $"{picture.OrigTime.Year}-{picture.OrigTime.Month}"), picture.Name);
            string thumb    = DirTool.Combine(DirTool.Combine(path, "_data", "thumb", $"{picture.Model}", $"{picture.OrigTime.Year}-{picture.OrigTime.Month}"), picture.Name);
            string original = DirTool.Combine(DirTool.Combine(path, $"{picture.Model}", $"{picture.OrigTime.Year}-{picture.OrigTime.Month}"), picture.Name);
            string info     = DirTool.Combine(DirTool.Combine(path, "_data", "info", $"{picture.Model}", $"{picture.OrigTime.Year}-{picture.OrigTime.Month}"), picture.Name + ".info");

            if (File.Exists(normal) && File.Exists(thumb) && File.Exists(original) && File.Exists(info))
            {
                return(true);
            }
            return(false);
        }
예제 #3
0
파일: Form1.cs 프로젝트: zyj0021/Fork
 /// <summary>
 /// 清理之前版本遗留文件及空文件夹
 /// </summary>
 /// <returns></returns>
 void CleanFile()
 {
     UIPbStatus(0);
     #region  除下载的更新文件和版本文件
     try
     {
         Directory.Delete(R.AppPath + @"Temp\Update\", true);
         File.Delete(R.VersionFile);
     }
     catch { }
     #endregion
     UIPbStatus(50);
     if (version.DoClean)
     {
         #region  除非当前版本文件
         List <string> file = FileTool.GetAllFile(R.AppPath);
         if (!ListTool.IsNullOrEmpty(file))
         {
             foreach (var f in file)
             {
                 int c = version.FileList.Where(x => x.File == "\\" + f.Replace(R.AppPath, "")).Count();
                 if (c == 0)
                 {
                     try { File.Delete(f); } catch { }
                 }
             }
             Thread.Sleep(R.cst.WAIT_TIME);
         }
         #endregion
         #region  除空文件夹
         List <string> path = DirTool.GetAllPath(R.AppPath);
         if (!ListTool.IsNullOrEmpty(path))
         {
             path = path.OrderByDescending(x => x).ToList();
             foreach (var p in path)
             {
                 if (Directory.GetFiles(p).Length == 0 && Directory.GetDirectories(p).Length == 0)
                 {
                     if (Directory.Exists(p))
                     {
                         try { Directory.Delete(p); } catch { }
                     }
                 }
                 Thread.Sleep(R.cst.WAIT_TIME);
             }
         }
         #endregion
     }
     UIPbStatus(100);
     Step = 5;
 }
예제 #4
0
        /// <summary>
        /// 定时处理要备份的文件任务
        /// </summary>
        private void BackupFileTask()
        {
            while (IsStart)
            {
                if (ListTool.HasElements(BackupFiles))
                {
                    //获取要备份的文件列表并复制样本
                    List <string> temp;
                    lock (BackupFiles)
                    {
                        temp        = BackupFiles;
                        BackupFiles = new List <string>();
                    }

                    using (var db = new Muse())
                    {
                        foreach (var t in temp)
                        {
                            //要备份的文件存在
                            if (File.Exists(t))
                            {
                                //文件属于要备份的文件目录
                                string      filepath = DirTool.GetFilePath(t);
                                BackupPaths path     = Paths.FirstOrDefault(x => filepath.Contains(x.Path));
                                if (path != null)
                                {
                                    //文件的MD5码以前没有备份过
                                    string md5    = FileTool.GetMD5(t);
                                    bool   isback = db.Any <BackupFiles>(x => x.FullPath == t && x.Md5 == md5, null);
                                    if (!isback)
                                    {
                                        string pathname  = path.Path;                                                                           //备份文件夹路径
                                        string pathalias = path.Alias;                                                                          //备份文件夹别名
                                        string pathfile  = t.Substring(pathname.Length, t.Length - pathname.Length);                            //截取备份文件子目录(相对备份文件夹)
                                        string fileext   = "." + DateTimeConvert.CompactString(DateTime.Now) + Path.GetExtension(t);            //设置后缀
                                        string fullpath  = DirTool.Combine(R.Settings.FileBackup.FileManBackup, pathalias, pathfile + fileext); //组合路径

                                        //删除冗余
                                        DeleteExcess(t);
                                        //备份文件
                                        BackupFile(t, fullpath, md5);
                                        _FileCount++;
                                    }
                                }
                            }
                        }
                    }
                }
                Thread.Sleep(R.Settings.FileBackup.BACK_UP_INTERVAL);
            }
        }
예제 #5
0
 /// <summary>
 /// 定居
 /// </summary>
 /// <param name="path">定居路径</param>
 /// <param name="list">货物清单</param>
 /// <returns></returns>
 public static bool Settle(string path, Dictionary <string, string> list)
 {
     if (DirTool.Create(path))
     {
         if (list != null)
         {
             foreach (var l in list)
             {
                 FileTool.Copy(l.Key, l.Value, true);
             }
         }
     }
     return(IsSettle(path, list));
 }
예제 #6
0
파일: TxtTool.cs 프로젝트: Crazyers/Fork
 public static bool Create(string file, string txt)
 {
     try
     {
         DirTool.Create(Path.GetDirectoryName(file));
         using (StreamWriter sw = new StreamWriter(file, false, Encoding.UTF8))
         {
             sw.WriteLine(txt);
         }
         return(true);
     }
     catch (Exception e) { }
     return(false);
 }
예제 #7
0
 public static bool write(string file, byte[] bytes)
 {
     try
     {
         DirTool.Create(Path.GetDirectoryName(file));
         //创建一个文件流
         using (FileStream fs = new FileStream(file, FileMode.OpenOrCreate))
         {
             //将byte数组写入文件中
             fs.Write(bytes, 0, bytes.Length);
         }
         return(true);
     }
     catch { }
     return(false);
 }
예제 #8
0
 private static void WriteFile(LogType type, string message)
 {
     if (IsWriteFile)
     {
         lock (LogFileLock)
         {
             //设置日志目录
             string logPath = AppDomain.CurrentDomain.BaseDirectory + "Log";
             string file    = string.Format(@"{0}\{1}.txt", logPath, DateTime.Now.ToString("yyyy-MM-dd"));
             //创建日志目录
             DirTool.Create(logPath);
             //写出日志
             TxtTool.Append(file, string.Format(LogFormat, DateTime.Now.ToString(TimeFormat), type.ToString(), message));
         }
     }
 }
예제 #9
0
        /// <summary>
        /// 启动最新版本程序
        /// </summary>
        /// <param name="route">路径:程序版本文件夹路径</param>
        /// <param name="startfilename">可执行文件名</param>
        /// <returns></returns>
        public static bool StartNewVersion(string route, string startfilename)
        {
            //判断路径是文件还是文件夹,并统一处理为文件夹
            string appPath = route;

            if (FileTool.IsFile(route))
            {
                appPath = DirTool.GetFilePath(route);
            }

            if (Directory.Exists(appPath))
            {
                //获取运行目录下所有文件
                List <string> paths = DirTool.GetPath(appPath);
                if (ListTool.HasElements(paths))
                {
                    //解析属于版本号的文件
                    Version version   = null;
                    string  startfile = null;
                    foreach (var path in paths)
                    {
                        //只解析文件名带三个点的文件夹
                        string filename = Path.GetFileName(path);
                        if (StringTool.SubStringCount(filename, ".") == 3)
                        {
                            try
                            {
                                Version tempVersion = new Version(filename);
                                string  tempFile    = DirTool.Combine(path, startfilename);
                                if ((version == null || tempVersion > version) && File.Exists(tempFile))
                                {
                                    version   = tempVersion;
                                    startfile = tempFile;
                                }
                            }
                            catch { }
                        }
                    }
                    //准备启动
                    if (startfile != null)
                    {
                        return(ProcessTool.Start(startfile));
                    }
                }
            }
            return(false);
        }
예제 #10
0
파일: Form1.cs 프로젝트: zyj0021/Fork
 /// <summary>
 /// 下载程序文件
 /// </summary>
 /// <returns></returns>
 bool DownloadFile(string downloadPath)
 {
     if (DirTool.Create(downloadPath))
     {
         FileCodeTool fcode = new FileCodeTool();
         for (int i = 0; i < version.FileList.Count; i++)
         {
             string fileName   = Path.GetFileName(version.FileList[i].File);
             string sourceFile = version.ServerPath + version.FileList[i].File;
             string destFile   = downloadPath + version.FileList[i].File;
             string destPath   = destFile.Substring(0, destFile.Length - fileName.Length);
             if (DirTool.Create(destPath))
             {
                 if (File.Exists(R.AppPath + version.FileList[i].File) &&
                     version.FileList[i].MD5 == fcode.GetMD5(R.AppPath + version.FileList[i].File))
                 {
                     UIDgvFileListUpdate(i, "ColDown", R.cst.FILE_JUMP);
                 }
                 else
                 {
                     FtpTool ftp = new FtpTool(R.FtpIp, R.FtpAccount, R.FtpPassword);
                     if (!ftp.DownloadFile(sourceFile, destPath))
                     {
                         if (!ftp.DownloadFile(sourceFile, destPath))
                         {
                             if (!ftp.DownloadFile(sourceFile, destPath))
                             {
                                 MessageBox.Show("更新文件无法被下载,请检查网络重试,谢谢。", "网络故障");
                                 Step  = 5;
                                 Error = -201;
                                 return(false);
                             }
                         }
                     }
                     UIDgvFileListUpdate(i, "ColDown", R.cst.FILE_SUCC);
                 }
             }
             else
             {
                 UIDgvFileListUpdate(i, "ColDown", R.cst.FILE_FAIL);
             }
             Thread.Sleep(R.cst.WAIT_TIME);
         }
     }
     Step = 3;
     return(true);
 }
예제 #11
0
        /// <summary>
        /// 获取最新版本号
        /// </summary>
        /// <param name="route">路径:程序版本文件夹路径</param>
        /// <param name="exeFile">可执行文件名</param>
        /// <returns></returns>
        public static bool GetNewVersion(string route, string exeFile, out Version version, out string startFile)
        {
            version   = null;
            startFile = "";

            //判断路径是文件还是文件夹,并统一处理为文件夹
            string appPath = route;

            if (FileTool.IsFile(route))
            {
                appPath = DirTool.GetFilePath(route);
            }

            if (Directory.Exists(appPath))
            {
                //获取运行目录下所有文件
                List <string> paths = DirTool.GetPath(appPath);
                if (ListTool.HasElements(paths))
                {
                    foreach (var path in paths)
                    {
                        //只解析文件名带三个点的文件夹
                        string filename = Path.GetFileName(path);
                        if (StringTool.SubStringCount(filename, ".") == 3)
                        {
                            try
                            {
                                Version tempVersion = new Version(filename);
                                string  tempFile    = DirTool.Combine(path, exeFile);
                                if ((version == null || tempVersion > version) && File.Exists(tempFile))
                                {
                                    version   = tempVersion;
                                    startFile = tempFile;
                                }
                            }
                            catch { }
                        }
                    }
                }
            }
            if (version != null && Str.Ok(startFile))
            {
                return(true);
            }
            return(false);
        }
예제 #12
0
        private void 保存屏幕ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Bitmap screen = null;

            try
            {
                string file = DirTool.Combine(R.Paths.App, DateTimeConvert.CompactString(DateTime.Now) + ".jpg");
                screen = ScreenCapture.Capture();
                screen.Save(file, System.Drawing.Imaging.ImageFormat.Jpeg);
                ToastForm.Display("保存", "保存屏幕成功:" + Path.GetFileName(file), ToastForm.ToastType.info);
            }
            catch { ToastForm.Display("保存", "保存屏幕失败", ToastForm.ToastType.error); }
            finally
            {
                screen?.Dispose();
            }
        }
예제 #13
0
 public static bool Copy(string sourceFileName, string destFileName, bool overwrite)
 {
     if (File.Exists(sourceFileName))
     {
         string destPath = DirTool.GetFilePath(destFileName);
         if (DirTool.Create(destPath))
         {
             try
             {
                 File.Copy(sourceFileName, destFileName, overwrite);
                 return(true);
             }
             catch { }
         }
     }
     return(false);
 }
예제 #14
0
        private void BtAddPath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();

            dialog.Description = "请选择要备份的文件夹";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string selPath = dialog.SelectedPath;                                                                                    //获取选中的目录
                string path    = DirTool.Combine(selPath, "\\");                                                                         //格式化选中的目录
                string name    = DirTool.GetPathName(selPath);                                                                           //获取目录名称

                List <BackupPaths> clashPath = R.Services.FBS.Paths.Where(x => x.Path.Contains(path) || path.Contains(x.Path)).ToList(); //查询冲突项
                if (ListTool.HasElements(clashPath))
                {
                    string cp = "";
                    clashPath.ForEach(x => cp += (x.Path + ";"));
                    //存在重合目录
                    MessageBox.Show(string.Format("您当前选择路径:{0},与之前选择的目录:{1},存在嵌套包含关系,请先从备份目录中移除,然后重新添加。", path, cp));
                }
                else
                {
                    UIEnableButton(false);
                    Task.Factory.StartNew(() =>
                    {
                        using (var db = new Muse())
                        {
                            if (!db.Do <BackupPaths>().Any(x => x.Path == path))
                            {
                                BackupPaths bp = new BackupPaths()
                                {
                                    Path = path, Alias = Guid.NewGuid().ToString()
                                };
                                if (db.Add(bp) > 0)
                                {
                                    R.Services.FBS.Paths.Add(bp);             //添加到列表
                                    R.Services.FBS.AddToWatcherPath(bp.Path); //添加到监听
                                    UIDgvPathAdd(name, null);                 //添加到列表UI
                                }
                            }
                        }
                        UIEnableButton(true);
                    });
                }
            }
        }
예제 #15
0
 public static void AfterUpdate(List <string> killProcess, List <string> startProcess)
 {
     if (ListTool.HasElements(killProcess))
     {
         foreach (var p in killProcess)
         {
             ProcessTool.KillProcess(p);
         }
     }
     if (ListTool.HasElements(startProcess))
     {
         foreach (var p in startProcess)
         {
             string file = DirTool.IsDriver(p) ? p : DirTool.Combine(R.Paths.ProjectRoot, p);
             ProcessTool.StartProcess(file);
         }
     }
 }
예제 #16
0
        /// <summary>
        /// 根据分类分配目录
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private string GetFilePath(LogType type)
        {
            string filePath = LogPath;

            switch (type)
            {
            case LogType.d: filePath = DirTool.Combine(LogPath, "debug"); break;

            case LogType.i: filePath = DirTool.Combine(LogPath, "information"); break;

            case LogType.e: filePath = DirTool.Combine(LogPath, "error"); break;

            case LogType.w: filePath = DirTool.Combine(LogPath, "warning"); break;

            case LogType.v: filePath = DirTool.Combine(LogPath, "verbose"); break;
            }
            return(filePath);
        }
예제 #17
0
 /// <summary>
 /// 写出运行时状态信息
 /// </summary>
 private void WriteStatus(FormActiveLogModel status)
 {
     try
     {
         if (status != null)// && Str.Ok(status.FormName, status.FormText))// && status.Duration > 0
         {
             //设置日志目录和日志文件
             string path = DirTool.Combine(LogPath, "form_active");
             string file = DirTool.Combine(path, DateTime.Now.ToString("yyyy-MM-dd") + ".txt");
             //创建日志目录
             DirTool.Create(path);
             //写出日志
             TxtTool.Append(file, status.ToString());
         }
         Cleaner();
     }
     catch { }
 }
예제 #18
0
 public static void BeforeUpdate(VersionModel vm)
 {
     if (ListTool.HasElements(vm.BeforeUpdateKillProcess))
     {
         foreach (var p in vm.BeforeUpdateKillProcess)
         {
             ProcessTool.KillProcess(p);
         }
     }
     if (ListTool.HasElements(vm.BeforeUpdateStartProcess))
     {
         foreach (var p in vm.BeforeUpdateStartProcess)
         {
             string file = DirTool.IsDriver(p) ? p : DirTool.Combine(R.Paths.ProjectRoot, p);
             ProcessTool.StartProcess(file);
         }
     }
 }
예제 #19
0
        public static void Clean(VersionModel vm)
        {
            //清理临时文件夹
            if (Directory.Exists(R.Paths.Temp))
            {
                try { Directory.Delete(R.Paths.Temp, true); } catch { }
            }
            //清理指定文件
            var cleanFile = vm.FileList.Where(x => x.IsClean == true);

            foreach (var file in cleanFile)
            {
                string fff = DirTool.IsDriver(file.LocalFile) ? file.LocalFile : R.Paths.ProjectRoot + file.LocalFile;
                if (File.Exists(fff))
                {
                    try { File.Delete(fff); } catch { }
                }
            }
        }
예제 #20
0
 /// <summary>
 /// 下载程序文件
 /// </summary>
 /// <returns></returns>
 bool DownloadFile(string downloadPath)
 {
     if (DirTool.Create(downloadPath))
     {
         FileCodeTool fcode = new FileCodeTool();
         for (int i = 0; i < version.FileList.Count; i++)
         {
             string fileName   = Path.GetFileName(version.FileList[i].File);
             string sourceFile = version.Path + version.FileList[i].File;
             string destFile   = downloadPath + version.FileList[i].File;
             string destPath   = destFile.Substring(0, destFile.Length - fileName.Length);
             if (DirTool.Create(destPath))
             {
                 try
                 {
                     if (File.Exists(AppDir + version.FileList[i].File) &&
                         version.FileList[i].MD5 == fcode.GetMD5(AppDir + version.FileList[i].File))
                     {
                         this.BeginInvoke(new Action(() => { UIDgvFileListUpdate(i, "ColDown", FILE_JUMP); }));
                     }
                     else
                     {
                         //File.Copy(sourceFile, destFile);
                         FtpHelper ftp = new FtpHelper(FtpIp, FtpAccount, FtpPassword);
                         ftp.DownloadFile(sourceFile, destPath);
                         this.BeginInvoke(new Action(() => { UIDgvFileListUpdate(i, "ColDown", FILE_SUCC); }));
                     }
                 }
                 catch (Exception e)
                 {
                     this.BeginInvoke(new Action(() => { UIDgvFileListUpdate(i, "ColDown", FILE_FAIL); }));
                 }
             }
             else
             {
                 this.BeginInvoke(new Action(() => { UIDgvFileListUpdate(i, "ColDown", FILE_FAIL); }));
             }
             Thread.Sleep(WAIT_TIME);
         }
     }
     return(false);
 }
예제 #21
0
파일: TxtTool.cs 프로젝트: Crazyers/Fork
 public static bool Append(string file, List <string> txt)
 {
     try
     {
         DirTool.Create(Path.GetDirectoryName(file));
         using (StreamWriter sw = new StreamWriter(file, true))
         {
             if (!ListTool.IsNullOrEmpty(txt))
             {
                 foreach (var t in txt)
                 {
                     sw.WriteLine(t);
                 }
             }
         }
         return(true);
     }
     catch (Exception e) { }
     return(false);
 }
예제 #22
0
        internal static string GetExe()
        {
            bool   Is64   = Environment.Is64BitOperatingSystem;
            string exe    = Is64 ? WIN10.X64 : WIN10.X32;
            OSName system = OSInfoTool.Caption();

            switch (system)
            {
            case OSName.WindowsXP: exe = Is64 ? XP.X64 : XP.X32; break;

            case OSName.Windows7: exe = Is64 ? WIN7.X64 : WIN7.X32; break;

            case OSName.Windows8Or81: exe = Is64 ? WIN8.X64 : WIN8.X32; break;

            case OSName.Windows10: exe = Is64 ? WIN10.X64 : WIN10.X32; break;
            }
            string file = DirTool.Combine(AppDomain.CurrentDomain.BaseDirectory, Root, exe);

            return(file);
        }
예제 #23
0
        /// <summary>
        /// 下载要更新的文件
        /// </summary>
        /// <param name="vm"></param>
        /// <returns></returns>
        private bool UpdateDownload(VersionModel vm)
        {
            FileCodeTool fcode    = new FileCodeTool();
            var          downFile = vm.FileList.Where(x => x.IsClean == false).ToList();

            if (vm != null && ListTool.HasElements(downFile))
            {
                for (int i = 0; i < downFile.Count(); i++)
                {
                    VersionFile file       = downFile[i];
                    string      serverFile = DirTool.Combine(vm.ServerPath, file.ServerFile);
                    string      tempFile   = DirTool.Combine(R.Paths.Temp, DownTemp, file.ServerFile);                                                 //下载到目标位置(带文件名)
                    string      localFile  = DirTool.IsDriver(file.LocalFile) ? file.LocalFile : DirTool.Combine(R.Paths.ProjectRoot, file.LocalFile); //旧文件位置
                    if (fcode.GetMD5(localFile) != file.FileMD5)
                    {
                        UIUpdateDetail("正在下载:" + Path.GetFileName(file.ServerFile));
                        R.Log.v(string.Format("{0} 文件有更新,正在下载文件", Path.GetFileName(file.ServerFile)));
                        FtpTool ftp = new FtpTool(R.Settings.FTP.Address, R.Settings.FTP.Account, R.Settings.FTP.Password);
                        if (!ftp.Download(serverFile, tempFile))
                        {
                            if (!ftp.Download(serverFile, tempFile))
                            {
                                if (!ftp.Download(serverFile, tempFile))
                                {
                                    R.Log.w(string.Format("{0} 文件下载失败", Path.GetFileName(file.ServerFile)));
                                    return(false);
                                }
                            }
                        }
                    }
                    else
                    {
                        UIUpdateDetail("文件已存在:" + Path.GetFileName(file.ServerFile));
                        R.Log.v(string.Format("{0} 文件不需要更新,已跳过该文件", Path.GetFileName(file.ServerFile)));
                    }
                    UIProgress(i + 1, downFile.Count());
                }
                return(true);
            }
            return(false);
        }
예제 #24
0
        /// <summary>
        /// 更新的完整流程
        /// </summary>
        /// <param name="vm"></param>
        /// <returns></returns>
        private bool Update(VersionModel vm)
        {
            VersionNumber = vm.VersionNumber;
            VersionDesc   = vm.VersionDesc;
            DownTemp      = Guid.NewGuid().ToString();
            BackupTemp    = Guid.NewGuid().ToString();
            if (DirTool.Create(R.Paths.Temp + DownTemp))
            {
                R.Log.i(string.Format("临时下载目录:{0},临时备份目录:{1},创建成功,准备更新", DownTemp, BackupTemp));
                UILoadVersion(vm);

                if (UpdateDownload(vm))
                {
                    R.Log.i("需要更新的文件已全部下载成功");
                    if (UpdateInsteadAndBackup(vm))
                    {
                        FileHelper.Clean(vm);
                        R.Log.i("更新文件已完成替换,清理列表和临时文件清理完成");
                        DataHelper.UpdatePluginConfig(vm);
                        DataHelper.UpdateWhatsnew(vm);
                        R.Log.i("更新插件配置信息,添加新版本特性说明完成");
                        UIUpdateDetail("添加新版本特性说明 Whatsnew.txt");
                        return(true);
                    }
                    else
                    {
                        UpdateRollback(vm);
                        R.Log.w("文件替换失败,当前更新失败,回滚备份的文件到该插件原始版本");
                    }
                }
                else
                {
                    R.Log.w("文件下载失败,当前更新失败");
                }
            }
            else
            {
                R.Log.i(string.Format("临时下载目录:{0},临时备份目录:{1},创建失败,取消本次更新", DownTemp, BackupTemp));
            }
            return(false);
        }
예제 #25
0
 private void WriteFile(LogModel log)
 {
     if (IsWriteFile)
     {
         lock (LogFileLock)
         {
             //设置日志目录
             string logPath = AppDomain.CurrentDomain.BaseDirectory + LogPath;
             string file    = string.Format(@"{0}\{1}.txt", logPath, DateTime.Now.ToString("yyyy-MM-dd"));
             //创建日志目录
             DirTool.Create(logPath);
             //写出日志
             TxtTool.Append(
                 file,
                 string.Format(LOG_FORMAT,
                               log.CreateTime.ToString(TIME_FORMAT),
                               log.Type.ToString(),
                               StringTool.ReplaceNewLine(log.Message)));
         }
     }
 }
예제 #26
0
파일: Log.cs 프로젝트: zuihoudehuhuan/Fork
 /// <summary>
 /// 写出到日志文件
 /// </summary>
 /// <param name="log"></param>
 private void WriteFile(LogModel log)
 {
     lock (LogFileLock)
     {
         //设置日志目录和日志文件
         string filePath = GetFilePath(log.Type);
         string file     = DirTool.Combine(filePath, DateTime.Now.ToString("yyyy-MM-dd") + ".txt");
         //创建日志目录
         DirTool.Create(filePath);
         //处理日志信息(换行)
         log.Message = Cons.FormatLine(log.Message);
         //写出日志
         TxtTool.Append(
             file,
             string.Format(LOG_FORMAT,
                           log.CreateTime.ToString(TIME_FORMAT),
                           log.Type.ToString(),
                           log.Message));
         Cleaner(log.Type);
     }
 }
예제 #27
0
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="info">新版本信息</param>
        /// <param name="tempPath">文件下载位置</param>
        /// <param name="dictionary">文件相对位置字典</param>
        /// <param name="downProgress">下载进度回调</param>
        /// <param name="downSender">下载进度事件数据</param>
        /// <param name="releaseProgress">释放进度回调</param>
        /// <param name="releaseSender">释放进度事件数据</param>
        /// <returns>
        /// -10000;//没有新版本
        /// -20000;//文件下载失败
        /// -30000;//文件释放失败
        /// </returns>
        public int Update(AppUpdateInfo info, string tempPath, Dictionary <string, string> dictionary,
                          ProgressDelegate.ProgressHandler downProgress    = null, object downSender    = null,
                          ProgressDelegate.ProgressHandler releaseProgress = null, object releaseSender = null)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            //请求最新版本信息
            if (info != null)
            {
                string file = DirTool.Combine(tempPath, GuidTool.Short() + "-" + info.Version);
                //准备更新(下载)
                string downfile = Download(file, info, downProgress, downSender);
                if (!string.IsNullOrWhiteSpace(downfile) && File.Exists(downfile))
                {
                    //格式化释放文件目录(相对路径转换为绝对路径)
                    string releasepath = AppDirTool.Get(info.ReleasePath, dictionary);
                    //释放文件,释放完成后删除临时文件
                    int unpackCode = FilePackageTool.Unpack(downfile, releasepath, releaseProgress, releaseSender);
                    File.Delete(file);
                    if (unpackCode > 0)
                    {
                        stopwatch.Stop();
                        return((int)stopwatch.Elapsed.TotalSeconds);
                    }
                    else
                    {
                        return(-30000 + unpackCode);//文件释放失败
                    }
                }
                else
                {
                    return(-20000);//文件下载失败
                }
            }
            else
            {
                return(-10000);//没有新版本
            }
        }
예제 #28
0
        private void CreateVersionMap()
        {
            string versionNumber = TbVersionNumber.Text;
            string ftpPath       = TbFtpPath.Text;

            string[] beginClose = TbBeginClose.Text.Split(';');
            string[] endRun     = TbEndRun.Text.Split(';');

            string       path       = TbPath.Text;
            string       parentPath = DirTool.Parent(path);
            FileCodeTool fcode      = new FileCodeTool();

            if (Directory.Exists(path) && Directory.Exists(parentPath))
            {
                List <string> fileList = FileTool.GetAllFile(path);
                if (!ListTool.IsNullOrEmpty(fileList))
                {
                    VersionModel version = new VersionModel()
                    {
                        Number            = versionNumber,
                        ServerPath        = ftpPath,
                        BeginCloseProcess = beginClose,
                        EndRunProcess     = endRun,
                        FileList          = new List <VersionFile>()
                    };

                    foreach (var item in fileList)
                    {
                        version.FileList.Add(new VersionFile()
                        {
                            File = item.Replace(path, ""),
                            MD5  = fcode.GetMD5(item),
                        });
                    }
                    string file = string.Format(@"{0}\update.version", parentPath, versionNumber);
                    string json = JsonTool.ToStr(version);
                    TxtTool.Create(file, json);
                }
            }
        }
예제 #29
0
        /// <summary>
        /// 查询是否有最新版本程序可以执行
        /// </summary>
        /// <param name="route">路径:程序版本文件夹路径</param>
        /// <param name="startfilename">可执行文件名</param>
        /// <returns></returns>
        public static bool HasNewVersion(string route, string startfilename)
        {
            //判断路径是文件还是文件夹,并统一处理为文件夹
            string appPath = route;

            if (FileTool.IsFile(route))
            {
                appPath = DirTool.GetFilePath(route);
            }

            if (Directory.Exists(appPath))
            {
                //获取运行目录下所有文件
                List <string> paths = DirTool.GetPath(appPath);
                if (ListTool.HasElements(paths))
                {
                    //解析属于版本号的文件
                    foreach (var path in paths)
                    {
                        //只解析文件名带三个点的文件夹
                        string filename = Path.GetFileName(path);
                        if (StringTool.SubStringCount(filename, ".") == 3)
                        {
                            try
                            {
                                //有版本命名的文件,且文件中有exe程序
                                Version tempVersion = new Version(filename);
                                string  tempFile    = DirTool.Combine(path, startfilename);
                                if (File.Exists(tempFile))
                                {
                                    return(true);
                                }
                            }
                            catch { }
                        }
                    }
                }
            }
            return(false);
        }
예제 #30
0
 /// <summary>
 /// 备份程序文件
 /// </summary>
 /// <returns></returns>
 bool BackupFile(string backupPath, string downloadPath)
 {
     if (DirTool.Create(backupPath))
     {
         FileCodeTool fcode = new FileCodeTool();
         for (int i = 0; i < version.FileList.Count; i++)
         {
             string fileName     = Path.GetFileName(version.FileList[i].File);
             string sourceFile   = AppDir + version.FileList[i].File;
             string destFile     = backupPath + version.FileList[i].File;
             string destPath     = destFile.Substring(0, destFile.Length - fileName.Length);
             string downloadFile = downloadPath + version.FileList[i].File;
             if (DirTool.Create(destPath))
             {
                 try
                 {
                     if (File.Exists(sourceFile) && File.Exists(downloadFile) && version.FileList[i].MD5 != fcode.GetMD5(AppDir + version.FileList[i].File))
                     {
                         File.Copy(sourceFile, destFile);
                         this.BeginInvoke(new Action(() => { UIDgvFileListUpdate(i, "ColBack", FILE_SUCC); }));
                     }
                     else
                     {
                         this.BeginInvoke(new Action(() => { UIDgvFileListUpdate(i, "ColBack", FILE_JUMP); }));
                     }
                 }
                 catch (Exception e)
                 {
                     this.BeginInvoke(new Action(() => { UIDgvFileListUpdate(i, "ColBack", FILE_FAIL); }));
                 }
             }
             else
             {
                 this.BeginInvoke(new Action(() => { UIDgvFileListUpdate(i, "ColBack", FILE_FAIL); }));
             }
             Thread.Sleep(WAIT_TIME);
         }
     }
     return(false);
 }