Exemplo n.º 1
0
        /// <summary>
        /// 写出运行时状态信息
        /// </summary>
        private void WriteStatus(StatusLogModel status)
        {
            try
            {
                if (status != null)
                {
                    //处理比率
                    status.Long = status.Long / 1000;
                    status.AFK  = status.AFK / 1000;
                    if (status.AFK > status.Long)
                    {
                        status.AFK = status.Long;
                    }

                    //设置日志目录和日志文件
                    string path = DirTool.Combine(LogPath, "status");
                    string file = DirTool.Combine(path, DateTime.Now.ToString("yyyy-MM-dd") + ".txt");
                    //创建日志目录
                    DirTool.Create(path);
                    //写出日志
                    TxtTool.Append(file, status.ToString());
                }
                Cleaner();
            }
            catch { }
        }
Exemplo n.º 2
0
        private PerformanceCounter ComputerProcessor = ComputerStatusTool.Processor(); //电脑CPU监控
        #endregion

        public void SetLogPath(string path)
        {
            if (!string.IsNullOrWhiteSpace(path))
            {
                LogPath = DirTool.Combine(path, LOG_PATH);
            }
        }
Exemplo n.º 3
0
        private void Form1_Load(object sender, EventArgs e)
        {
            Azylee.YeahWeb.ExtWebAPI.BingWebAPI.WallpaperUtils.WallpaperTool.GetLast10Days();

            List <string> file_list = new List <string>();
            var           md        = Azylee.YeahWeb.ExtWebAPI.BingWebAPI.WallpaperUtils.WallpaperTool.GetToday();
            var           md2       = Azylee.YeahWeb.ExtWebAPI.BingWebAPI.WallpaperUtils.WallpaperTool.GetYesterday();

            if (md != null && Ls.Ok(md.images))
            {
                foreach (var item in md.images)
                {
                    string image_url   = item.GetImageUrl();
                    string file_path   = DirTool.Combine(@"F:\imgs", item.hsh + ".jpg");
                    bool   down_result = HttpTool.Download(image_url, file_path);
                    if (down_result)
                    {
                        file_list.Add(file_path);
                    }
                }
            }
            //string a = WallpaperTool.Get();

            //bool b = WallpaperTool.Set(@"C:\Users\yuzhengyang\Pictures\\cc.jpg");

            //Bitmap b1 = new Bitmap(@"F:\图片压缩测试\未标题-1.jpg");
            //byte[] b1_byte = IMG.Compression(b1, 30);
            //File.WriteAllBytes(@"F:\图片压缩测试\未标题-1(Compression).jpg", b1_byte);
        }
Exemplo n.º 4
0
        private void btPackage_Click(object sender, EventArgs e)
        {
            string src  = tbPath.Text;
            string file = tbName.Text + "-" + tbVersion.Text.Replace('.', '-') + ".udp";
            string dst  = DirTool.Combine(DirTool.GetFilePath(tbPath.Text), file);

            if (FilePackageTool.Pack(src, dst) > 0 && File.Exists(dst))
            {
                string md5Code = FileTool.GetMD5(dst);
                //设置更新模型,14个属性
                AppUpdateInfo aui = new AppUpdateInfo()
                {
                    Name         = tbName.Text,
                    Author       = tbAuthor.Text,
                    Desc         = tbDesc.Text,
                    Version      = tbVersion.Text,
                    ReleasePath  = tbReleasePath.Text,
                    Necessary    = cbNecessary.Checked,
                    DateTime     = DateTime.Now,
                    DownloadMode = rbHttpMode.Checked ? 0 : 1,
                    HttpUrl      = tbHttpUrl.Text,
                    FtpIp        = tbFtpIp.Text,
                    FtpAccount   = tbFtpAccount.Text,
                    FtpPassword  = tbFtpPassword.Text,
                    FtpFile      = tbFtpFile.Text,
                    Md5          = md5Code,
                };
                string auiJson = JsonTool.ToStr(aui);
                TxtTool.Create(dst + ".txt", auiJson);
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// 清理过多的状态信息文件
        /// </summary>
        private void Cleaner()
        {
            string        path  = DirTool.Combine(LogPath, "status");
            List <string> files = FileTool.GetFile(path);

            if (ListTool.HasElements(files))
            {
                files.ForEach(f =>
                {
                    try
                    {
                        string filename = Path.GetFileNameWithoutExtension(f);
                        if (filename.Length == 10)
                        {
                            DateTime date = DateTime.Parse(filename);
                            if (date < Time.AddDays(-CACHE_DAYS - 1))
                            {
                                FileTool.Delete(f);
                            }
                        }
                        else
                        {
                            FileTool.Delete(f);
                        }
                    }
                    catch { FileTool.Delete(f); }
                });
            }
        }
Exemplo n.º 6
0
        private void BTPack_Click(object sender, EventArgs e)
        {
            string src  = TBPath.Text;
            string file = Path.GetFileName(src) + ".package";
            string dst  = DirTool.Combine(DirTool.GetFilePath(TBPath.Text), file);

            FilePackageTool.Pack(src, dst);
        }
Exemplo n.º 7
0
        /// <summary>
        /// 整理图片到指定位置
        /// </summary>
        /// <param name="file">图片路径</param>
        /// <param name="path">整理目标路径</param>
        /// <param name="picture">图片信息模型</param>
        /// <returns></returns>
        public static bool ReorganizePicture(string file, string path, Pictures picture)
        {
            try
            {
                if (File.Exists(file))
                {
                    //根据照片信息旋转,生成临时文件
                    string temp = DirTool.Combine(path, "_data", "temp");
                    DirTool.Create(temp);
                    string tempfile = DirTool.Combine(temp, picture.Name);
                    if (File.Exists(tempfile))
                    {
                        FileTool.Delete(tempfile);
                    }
                    RotateImageTool.Rotate(file, tempfile);

                    //创建压缩图
                    string normal = DirTool.Combine(path, "_data", "normal", $"{picture.Model}", $"{picture.OrigTime.Year}-{picture.OrigTime.Month}");
                    DirTool.Create(normal);
                    if (File.Exists(DirTool.Combine(normal, picture.Name)))
                    {
                        FileTool.Delete(DirTool.Combine(normal, picture.Name));
                    }
                    ImageHelper.MakeThumbnail(tempfile, DirTool.Combine(normal, picture.Name), 1000, 1000, "H");

                    //创建缩略图
                    string thumb = DirTool.Combine(path, "_data", "thumb", $"{picture.Model}", $"{picture.OrigTime.Year}-{picture.OrigTime.Month}");
                    DirTool.Create(thumb);
                    if (File.Exists(DirTool.Combine(thumb, picture.Name)))
                    {
                        FileTool.Delete(DirTool.Combine(thumb, picture.Name));
                    }
                    ImageHelper.MakeThumbnail(tempfile, DirTool.Combine(thumb, picture.Name), 500, 500, "Cut");

                    //整理原始照片
                    string original = DirTool.Combine(path, $"{picture.Model}", $"{picture.OrigTime.Year}-{picture.OrigTime.Month}");
                    DirTool.Create(original);
                    if (File.Exists(DirTool.Combine(original, picture.Name)))
                    {
                        FileTool.Delete(DirTool.Combine(original, picture.Name));
                    }
                    File.Move(file, DirTool.Combine(original, picture.Name));

                    //整理照片基础信息
                    string info = DirTool.Combine(path, "_data", "info", $"{picture.Model}", $"{picture.OrigTime.Year}-{picture.OrigTime.Month}");
                    DirTool.Create(info);
                    TxtTool.Create(DirTool.Combine(info, picture.Name + ".info"), JsonTool.ToStr(picture));

                    FileTool.Delete(tempfile);
                    return(true);
                }
            }
            catch { return(false); }
            return(false);
        }
Exemplo n.º 8
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);
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// 写出资源配置信息
        /// </summary>
        private void WriteConfig()
        {
            //记录固定资源信息
            string path = DirTool.Combine(LogPath, "resource");
            string file = DirTool.Combine(path, "computer.ini");

            //创建目录
            DirTool.Create(path);
            //写出信息
            IniTool.WriteValue(file, "system", "ram", ComputerInfoTool.TotalPhysicalMemory().ToString());
            IniTool.WriteValue(file, "system", "drive", ComputerInfoTool.GetSystemDriveTotalSize().ToString());
        }
Exemplo n.º 10
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);
        }
Exemplo n.º 11
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);
            }
        }
Exemplo n.º 12
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);
        }
Exemplo n.º 13
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();
            }
        }
Exemplo n.º 14
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);
        }
Exemplo n.º 15
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);
                    });
                }
            }
        }
Exemplo n.º 16
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 { }
 }
Exemplo n.º 17
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);
         }
     }
 }
Exemplo n.º 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);
         }
     }
 }
Exemplo n.º 19
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);
        }
Exemplo n.º 20
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);
        }
Exemplo n.º 21
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);
        }
Exemplo n.º 22
0
 /// <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);
     }
 }
Exemplo n.º 23
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);
        }
Exemplo n.º 24
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);//没有新版本
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// 更新回滚
        /// </summary>
        /// <param name="vm"></param>
        private void UpdateRollback(VersionModel vm)
        {
            var backFile = vm.FileList.Where(x => x.IsClean == false);

            foreach (var file in backFile)
            {
                string tempBack  = DirTool.Combine(R.Paths.Temp, BackupTemp, file.ServerFile);                                               //备份到目标位置(带文件名)
                string localFile = DirTool.IsDriver(file.LocalFile) ? file.LocalFile : DirTool.Combine(R.Paths.ProjectRoot, file.LocalFile); //旧文件位置

                //还原备份文件
                if (File.Exists(tempBack))
                {
                    try
                    {
                        DirTool.Create(DirTool.GetFilePath(localFile));
                        File.Copy(tempBack, localFile, true);
                        UIUpdateDetail("正在还原备份文件:" + Path.GetFileName(file.LocalFile));
                    }
                    catch (Exception e) { }
                }
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// 备份并替换文件
        /// </summary>
        /// <param name="vm"></param>
        /// <returns></returns>
        private bool UpdateInsteadAndBackup(VersionModel vm)
        {
            var insteadFile = vm.FileList.Where(x => x.IsClean == false);

            foreach (var file in insteadFile)
            {
                string tempDown  = DirTool.Combine(R.Paths.Temp, DownTemp, file.ServerFile);                                                 //下载到目标位置(带文件名)
                string tempBack  = DirTool.Combine(R.Paths.Temp, BackupTemp, file.ServerFile);                                               //备份到目标位置(带文件名)
                string localFile = DirTool.IsDriver(file.LocalFile) ? file.LocalFile : DirTool.Combine(R.Paths.ProjectRoot, file.LocalFile); //旧文件位置

                //备份文件
                if (File.Exists(localFile) && File.Exists(tempDown))
                {
                    try
                    {
                        DirTool.Create(DirTool.GetFilePath(tempBack));
                        File.Copy(localFile, tempBack, true);
                        UIUpdateDetail("正在备份:" + Path.GetFileName(tempBack));
                    }
                    catch (Exception e) { }
                }
                //替换文件
                if (File.Exists(tempDown))
                {
                    try
                    {
                        DirTool.Create(DirTool.GetFilePath(localFile));
                        File.Copy(tempDown, localFile, true);
                        UIUpdateDetail("正在更新:" + Path.GetFileName(file.LocalFile));
                    }
                    catch (Exception e)
                    {
                        return(false);
                    }
                }
            }
            return(true);
        }
Exemplo n.º 27
0
 private void ConnectLocalByProcess()
 {
     try
     {
         Process[] process = Process.GetProcessesByName("USBManager.Service");
         if (Ls.Ok(process))
         {
             string file = process[0].MainModule.FileName;
             if (File.Exists(file))
             {
                 string path     = DirTool.Parent(file);
                 string set_file = DirTool.Combine(path, "USBManagerServiceSettings.ini");
                 int    port     = IniTool.GetInt(set_file, "Tx", "TcppPort", 0);
                 if (port > 0)
                 {
                     Connect("127.0.0.1", port);
                     Close();
                 }
             }
         }
     }
     catch { }
 }
Exemplo n.º 28
0
        private void ProjectItemPart_Load(object sender, EventArgs e)
        {
            //启动按钮默认不可用(Init初始化后变为可用)
            BTStartOrStop.Enabled = false; //禁止启动/关闭
            BTAddNew.Enabled      = false; //禁止装载新版本
            CBVersion.Enabled     = false; //禁止选择启动版本

            //持续监控端口及端口进程状态
            ProcessStatus();

            //加载项目资料(加载前检查是否存在)
            if (File.Exists(DirTool.Combine(R.Paths.Projects, Name)))
            {
                string txt = TxtTool.Read(DirTool.Combine(R.Paths.Projects, Name));
                var    p   = Json.String2Object <ProjectModel>(txt);
                if (p != null)
                {
                    SetProject(p);
                }
            }

            //将控件加入到管理列表中
            R.ProjectItems.Add(this);
        }
Exemplo n.º 29
0
        /// <summary>
        /// 文件打包
        /// </summary>
        /// <param name="srcPath">要打包的路径</param>
        /// <param name="dstFile">打包后的文件</param>
        /// <param name="progress">回调进度</param>
        /// <param name="overwrite">覆盖打包后的文件(重复时)</param>
        /// <returns>
        /// -11;//要打包的路径不存在
        /// -12;//打包后的目标文件已存在
        /// -13;//要打包的路径中没有文件
        /// -14;//输出文件夹不存在
        /// -404;//未知错误,操作失败
        /// </returns>
        public static int Pack(string srcPath, string dstFile, ProgressDelegate.ProgressHandler progress = null, object sender = null, bool overwrite = true)
        {
            DateTime beginTime = DateTime.Now;

            if (!Directory.Exists(srcPath))
            {
                return(-11);                           //要打包的路径不存在
            }
            if (File.Exists(dstFile) && !overwrite)
            {
                return(-12);                                   //打包后的目标文件已存在
            }
            if (!DirTool.Create(DirTool.GetFilePath(dstFile)))
            {
                return(-14);                                              //输出文件夹不存在
            }
            List <string>           tempfiles = FileTool.GetAllFile(srcPath);
            List <FilePackageModel> files     = CreateFilePackageModel(tempfiles, srcPath);

            if (ListTool.HasElements(files))
            {
                long allfilesize     = files.Sum(x => x.Size); //文件总大小
                long surplusfilesize = allfilesize;            //剩余要写入的文件大小
                using (FileStream fsWrite = new FileStream(dstFile, FileMode.Create))
                {
                    try
                    {
                        //写入文件类型标识和版本号
                        byte[] filetypeandversion = Encoding.Default.GetBytes(FileType + FileVersion);
                        fsWrite.Write(filetypeandversion, 0, filetypeandversion.Length);

                        //写入头部总长度
                        int    headl      = files.Sum(x => x.AllByteLength);
                        byte[] headlength = BitConverter.GetBytes(headl);
                        fsWrite.Write(headlength, 0, headlength.Length);
                        //循环写入文件信息
                        files.ForEach(x =>
                        {
                            fsWrite.Write(x.NameLengthByte, 0, x.NameLengthByte.Length);
                            fsWrite.Write(x.NameByte, 0, x.NameByte.Length);
                            fsWrite.Write(x.PathLengthByte, 0, x.PathLengthByte.Length);
                            fsWrite.Write(x.PathByte, 0, x.PathByte.Length);
                            fsWrite.Write(x.SizeLengthByte, 0, x.SizeLengthByte.Length);
                            fsWrite.Write(x.SizeByte, 0, x.SizeByte.Length);
                            fsWrite.Write(x.MD5LengthByte, 0, x.MD5LengthByte.Length);
                            fsWrite.Write(x.MD5Byte, 0, x.MD5Byte.Length);
                        });
                        //循环写入文件
                        files.ForEach(x =>
                        {
                            //读取文件(可访问被打开的exe文件)
                            using (FileStream fsRead = new FileStream(DirTool.Combine(srcPath, x.Path, x.Name), FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                            {
                                int readCount = 0;
                                byte[] buffer = new byte[FileBuffer];
                                while ((readCount = fsRead.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    fsWrite.Write(buffer, 0, readCount);
                                    surplusfilesize -= readCount;
                                    progress?.Invoke(sender, new ProgressEventArgs(allfilesize - surplusfilesize, allfilesize));
                                }
                            }
                        });
                    }
                    catch (Exception e) { }
                }
                if (surplusfilesize == 0)
                {
                    return((int)Math.Ceiling((DateTime.Now - beginTime).TotalSeconds));//操作成功
                }
            }
            else
            {
                return(-13);//要打包的路径中没有文件
            }
            //打包失败后,删除打包后的文件
            try { File.Delete(dstFile); } catch (Exception e) { }
            return(-404);//未知错误,操作失败
        }
Exemplo n.º 30
0
        /// <summary>
        /// 拆包
        /// </summary>
        /// <param name="srcFile">包文件路径</param>
        /// <param name="dstPath">拆包到的目录 </param>
        /// <param name="progress">回调进度</param>
        /// <param name="overwrite">覆盖拆包后的文件(重复时)</param>
        /// <returns>
        /// -11; //要解包的文件不存在
        /// -12;//要解包的目标文件夹已存在
        /// -20;// 文件类型不匹配
        /// -99;//未知错误,操作失败
        /// </returns>
        public static int Unpack(string srcFile, string dstPath, ProgressDelegate.ProgressHandler progress = null, object sender = null, bool overwrite = true)
        {
            DateTime beginTime = DateTime.Now;

            if (!File.Exists(srcFile))
            {
                return(-11);                       //要解包的文件不存在
            }
            if (Directory.Exists(dstPath) && !overwrite)
            {
                return(-12);                                        //要解包的目标文件夹已存在
            }
            using (FileStream fsRead = new FileStream(srcFile, FileMode.Open))
            {
                try
                {
                    string version = GetFileVersion(fsRead);
                    if (version == null)
                    {
                        return(-20);                // 文件类型不匹配
                    }
                    //读取头部总长度
                    byte[] headl      = new byte[4];
                    int    headlength = 0;
                    fsRead.Read(headl, 0, headl.Length);
                    headlength = BitConverter.ToInt32(headl, 0);
                    if (headlength > 0)
                    {
                        //读取文件列表信息
                        byte[] headdata = new byte[headlength];
                        fsRead.Read(headdata, 0, headlength);
                        List <FilePackageModel> files = GetFilePackageModel(headdata);
                        if (ListTool.HasElements(files))
                        {
                            long allfilesize = files.Sum(x => x.Size); //文件总大小
                            long current     = 0;                      //当前进度
                            //读取写出所有文件
                            files.ForEach(x =>
                            {
                                if (DirTool.Create(DirTool.Combine(dstPath, x.Path)))
                                {
                                    try
                                    {
                                        using (FileStream fsWrite = new FileStream(DirTool.Combine(dstPath, x.Path, x.Name), FileMode.Create))
                                        {
                                            long size     = x.Size;
                                            int readCount = 0;
                                            byte[] buffer = new byte[FileBuffer];

                                            while (size > FileBuffer)
                                            {
                                                readCount = fsRead.Read(buffer, 0, buffer.Length);
                                                fsWrite.Write(buffer, 0, readCount);
                                                size    -= readCount;
                                                current += readCount;
                                                progress?.Invoke(sender, new ProgressEventArgs(current, allfilesize));
                                            }
                                            if (size <= FileBuffer)
                                            {
                                                readCount = fsRead.Read(buffer, 0, (int)size);
                                                fsWrite.Write(buffer, 0, readCount);
                                                current += readCount;
                                                progress?.Invoke(sender, new ProgressEventArgs(current, allfilesize));
                                            }
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        fsRead.Seek(x.Size, SeekOrigin.Current);
                                        current += x.Size;
                                        progress?.Invoke(sender, new ProgressEventArgs(current, allfilesize));
                                    }
                                }
                            });
                            //验证文件列表
                            bool allCheck = true;
                            foreach (var file in files)
                            {
                                string temp   = DirTool.Combine(dstPath, file.Path, file.Name);
                                string tempCk = FileTool.GetMD5(temp);
                                if (tempCk != file.MD5)//验证文件(Size:速度会快一些,MD5在大文件的验证上非常耗时)
                                {
                                    allCheck = false;
                                    break;
                                }
                            }
                            if (allCheck)
                            {
                                return((int)Math.Ceiling((DateTime.Now - beginTime).TotalSeconds));         //操作成功
                            }
                        }
                    }
                }
                catch (Exception e) { }
            }
            return(-99);//未知错误,操作失败
        }