/// <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 { } }
/// <summary> /// 还原程序文件 /// </summary> /// <returns></returns> bool RollBackFile(string backupPath) { for (int i = 0; i < version.FileList.Count; i++) { string fileName = Path.GetFileName(version.FileList[i].File); string sourceFile = backupPath + version.FileList[i].File; string destFile = AppDir + version.FileList[i].File; string destPath = destFile.Substring(0, destFile.Length - fileName.Length); if (DirTool.Create(destPath)) { try { if (File.Exists(sourceFile)) { File.Copy(sourceFile, destFile, true); this.BeginInvoke(new Action(() => { UIDgvFileListUpdate(i, "ColRoll", FILE_SUCC); })); } else { this.BeginInvoke(new Action(() => { UIDgvFileListUpdate(i, "ColRoll", FILE_JUMP); })); } } catch (Exception e) { this.BeginInvoke(new Action(() => { UIDgvFileListUpdate(i, "ColRoll", FILE_FAIL); })); } } else { this.BeginInvoke(new Action(() => { UIDgvFileListUpdate(i, "ColRoll", FILE_FAIL); })); } Thread.Sleep(WAIT_TIME); } return(false); }
/// <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); }
/// <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); } }
/// <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()); }
/// <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)); }
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); }
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)); } } }
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); }
/// <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); }
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); }
/// <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 { } }
/// <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); }
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); }
/// <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); }
/// <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); } }
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))); } } }
/// <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); }
public static void Persistence() { DirTool.Create(R.Paths.Store); List <SystemStatusModel> ssm = new List <SystemStatusModel>(); List <ProjectStatusModel> psm = new List <ProjectStatusModel>(); foreach (var item in SystemStatus.ToArray()) { ssm.Add(item.Value); } foreach (var item in ProjectStatus.ToArray()) { psm.Add(item.Value); } string ss = Json.Object2String(ssm.OrderBy(x => x.IP)); string ps = Json.Object2String(psm.OrderBy(x => x.IP).ThenBy(x => x.Port)); bool ss_flag = TxtTool.Create(R.Files.SystemStatus, ss); bool ps_flag = TxtTool.Create(R.Files.ProjectStatus, ps); }
/// <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) { } } } }
private void WriteFile(List <LogModel> list) { 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); //整理要输出的内容 List <string> txts = new List <string>(); foreach (var item in list) { txts.Add(string.Format(LOG_FORMAT, item.CreateTime.ToString(TIME_FORMAT), item.Type.ToString(), item.Message)); } //写出日志 TxtTool.Append(file, txts); } } }
/// <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); }
private void BtRestoreToOld_Click(object sender, EventArgs e) { if (DgvFiles.CurrentRow != null && DgvFiles.CurrentRow.Index >= 0) { BackupFiles file = Files[DgvFiles.CurrentRow.Index]; string title = string.Format("文件还原", file.LastWriteTime); string text = string.Format("您确定将文件:{0} [ {1} ]{2}还原到:{2}{3} 吗?", Path.GetFileName(file.FullPath), file.LastWriteTime, Environment.NewLine, file.FullPath); if (MessageBox.Show(text, title, MessageBoxButtons.OKCancel) == DialogResult.OK) { string from = file.BackupFullPath; string to = file.FullPath; string topath = DirTool.GetFilePath(to); if (DirTool.Create(topath)) { File.Copy(from, to, true); } else { MessageBox.Show(string.Format("路径:{0} 不存在,请还原到其他路径。", topath), "路径不存在"); } } } }
/// <summary> /// 初始化Ini配置信息 /// </summary> static void InitIni() { DirTool.Create(R.Paths.Settings); DirTool.Create(R.Paths.Projects); DirTool.Create(R.Paths.DefaultPublishStorage); DirTool.Create(R.Paths.DefaultNewStorage); R.Paths.PublishStorage = IniTool.GetString(R.Files.Settings, "Paths", "PublishStorage", R.Paths.DefaultPublishStorage); if (string.IsNullOrWhiteSpace(R.Paths.PublishStorage)) { R.Paths.PublishStorage = R.Paths.DefaultPublishStorage; } R.Paths.NewStorage = IniTool.GetString(R.Files.Settings, "Paths", "NewStorage", R.Paths.DefaultNewStorage); if (string.IsNullOrWhiteSpace(R.Paths.NewStorage)) { R.Paths.NewStorage = R.Paths.DefaultNewStorage; } R.Tx.IP = IniTool.GetString(R.Files.Settings, "Console", "IP", ""); R.Tx.Port = IniTool.GetInt(R.Files.Settings, "Console", "Port", 0); R.Tx.LocalIP = IniTool.GetString(R.Files.Settings, "Local", "IP", ""); R.Tx.LocalName = IniTool.GetString(R.Files.Settings, "Local", "Name", ""); R.IsAutoDeleteExpiredLog = IniTool.GetBool(R.Files.Settings, "Settings", "AutoDeleteExpiredLog", false); R.AppID = IniTool.GetString(R.Files.Settings, "App", "ID", ""); if (!Str.Ok(R.AppID)) { R.AppID = GuidTool.Short(); IniTool.Set(R.Files.Settings, "App", "ID", R.AppID); } if (!File.Exists(R.Files.NewStorageReadme)) { TxtTool.Create(R.Files.NewStorageReadme, R.NewStorageReadmeTxt); } }
/// <summary> /// 更新程序文件 /// </summary> /// <returns></returns> bool UpdateFile(string downloadPath) { for (int i = 0; i < version.FileList.Count; i++) { string fileName = Path.GetFileName(version.FileList[i].File); string sourceFile = downloadPath + version.FileList[i].File; string destFile = R.AppPath + version.FileList[i].File; string destPath = destFile.Substring(0, destFile.Length - fileName.Length); if (DirTool.Create(destPath)) { try { if (File.Exists(sourceFile)) { File.Copy(sourceFile, destFile, true); UIDgvFileListUpdate(i, "ColUpdate", R.cst.FILE_SUCC); } else { UIDgvFileListUpdate(i, "ColUpdate", R.cst.FILE_JUMP); } } catch (Exception e) { UIDgvFileListUpdate(i, "ColUpdate", R.cst.FILE_FAIL); } } else { UIDgvFileListUpdate(i, "ColBack", R.cst.FILE_FAIL); } Thread.Sleep(R.cst.WAIT_TIME); } Step = 4; return(false); }
/// <summary> /// 备份文件 /// </summary> /// <param name="path"></param> /// <param name="newpath"></param> private void BackupFile(string path, string newpath, string md5) { using (var db = new Muse()) { try { if (DirTool.Create(DirTool.GetFilePath(newpath))) { string lastwritetime = DateTimeConvert.StandardString(File.GetLastWriteTime(path)); File.Copy(path, newpath, true); db.Add(new BackupFiles() { FullPath = path, BackupFullPath = newpath, Size = FileTool.Size(path), BackupTime = DateTimeConvert.StandardString(DateTime.Now), LastWriteTime = lastwritetime, Md5 = md5, }); } } catch (Exception e) { } } }
/// <summary> /// 装载新版本工程 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BTAddNew_Click(object sender, EventArgs e) { if (!string.IsNullOrWhiteSpace(Project.Folder) && !string.IsNullOrWhiteSpace(Project.JarFile)) { //查询New仓库中,该工程的新版本 string newPath = JarFileTool.GetNewPath(Project); if (Directory.Exists(newPath) && File.Exists(DirTool.Combine(newPath, Project.JarFile))) { try { ToastForm.Display("装载中", $"正在装载 {Project.Name} 的新版本...", 'i', 5000); //移动文件到发布仓库中 string aimPath = DirTool.Combine(R.Paths.PublishStorage, Project.Folder); //组合目标路径 DirTool.Create(aimPath); //创建目标路径 if (Directory.Exists(DirTool.Combine(aimPath, (Project.LastVersion + 1).ToString()))) //如果存在目标文件夹 { Directory.Delete(DirTool.Combine(aimPath, (Project.LastVersion + 1).ToString()), true); //删除目标文件夹(防止重复) } Directory.Move(newPath, DirTool.Combine(aimPath, (Project.LastVersion + 1).ToString())); //开始移动 //添加新版本信息 Project.LastVersion++; Project.CurrentVersion = Project.LastVersion; ProjectVersionModel version = new ProjectVersionModel() { CreateTime = DateTime.Now, Number = Project.LastVersion, }; if (Project.Versions == null) { Project.Versions = new List <ProjectVersionModel>(); } Project.Versions.Add(version); ToastForm.Display("装载成功", $"成功装载 {Project.Name} 的新版本", 'i', 5000); } catch { ToastForm.Display("装载失败", $"装载 {Project.Name} 的新版本失败", 'e', 5000); } } else { //没有发现新版本,不做处理 ToastForm.Display("装载失败", $"没有发现 {Project.Name} 的新版本", 'w', 5000); } } else { //没有工程配置信息,不做处理 ToastForm.Display("装载失败", $"没有发现工程的配置信息", 'e', 5000); } //清除多余版本 if (Project.VersionCache > 0 && !string.IsNullOrWhiteSpace(Project.Folder) && ListTool.HasElements(Project.Versions)) { if (Project.Versions.Count > Project.VersionCache) { List <ProjectVersionModel> _tempVers = Project.Versions.OrderByDescending(x => x.CreateTime).ToList(); List <ProjectVersionModel> _newVers = new List <ProjectVersionModel>(); for (int i = 0; i < Project.VersionCache; i++) { _newVers.Add(_tempVers[i]); } for (int i = Project.VersionCache; i < Project.Versions.Count; i++) { string path = DirTool.Combine(R.Paths.PublishStorage, Project.Folder, (_tempVers[i].Number).ToString()); try { //如果文件夹存在,则删除文件夹及内容 if (Directory.Exists(path)) { Directory.Delete(path, true); } } catch { //如果删除失败,则继续保留该版本,等待下次继续删除 _newVers.Add(_tempVers[i]); } } Project.Versions = _newVers; } } //重置项目信息 SetProject(Project); }
/// <summary> /// 获取要更新的插件列表 /// </summary> /// <returns></returns> public static List <PluginModel> GetPluginList() { #region 本地插件列表是否存在 if (!File.Exists(R.Files.Plugins)) { DirTool.Create(DirTool.GetFilePath(R.Files.Plugins)); //如果文件不存在 创建新的插件xml XElement xe = new XElement("Plugins"); xe.Save(R.Files.Plugins); } #endregion #region 读取本地插件列表 List <PluginModel> localPluginList = new List <PluginModel>(); try { XElement xe = XElement.Load(R.Files.Plugins); IEnumerable <XElement> elements = xe.Elements("Item"); if (ListTool.HasElements(elements)) { foreach (var ele in elements) { PluginModel plug = new PluginModel() { Name = ele.Attribute("Name").Value, Version = ele.Attribute("Version").Value }; localPluginList.Add(plug); } } } catch (Exception e) { } #endregion #region 读取服务器插件列表 List <PluginModel> serverPluginList = HttpTool.Get <List <PluginModel> >(R.Settings.Url.WebService + "getPluginsList"); #endregion #region 整理需要更新的插件列表 List <PluginModel> rs = new List <PluginModel>(); if (ListTool.HasElements(serverPluginList)) { serverPluginList.ForEach(p => { var tmp = localPluginList.FirstOrDefault(x => x.Name == p.Name); if (tmp == null) { //如果服务器有的插件,本地没有,则添加至需要更新的列表 rs.Add(p); } else { if (tmp.Version != p.Version) { //如果服务器插件版本和本机插件版本不同,则添加至需要更新列表 rs.Add(p); } } }); } #endregion return(rs); }
/// <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);//未知错误,操作失败 }
/// <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);//未知错误,操作失败 }