From a3bfee2755f09b97b06073d2587556e1c1cc0589 Mon Sep 17 00:00:00 2001
From: dong <1278815766@qq.com>
Date: Thu, 3 Jul 2025 12:46:26 +0800
Subject: [PATCH] =?UTF-8?q?7zdll=E7=9B=AE=E5=BD=95=E4=BF=AE=E6=94=B9?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
CheckDownload.csproj | 17 ++---
Form1.cs | 169 +++++++++++++++++--------------------------
2 files changed, 76 insertions(+), 110 deletions(-)
diff --git a/CheckDownload.csproj b/CheckDownload.csproj
index e95b072..a32b34e 100644
--- a/CheckDownload.csproj
+++ b/CheckDownload.csproj
@@ -184,24 +184,23 @@
-
+
PreserveNewest
-
-
+
这台计算机上缺少此项目引用的 NuGet 程序包。使用"NuGet 程序包还原"可下载这些程序包。有关更多信息,请参见 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。
+
+
+
-
-
-
-
-
-
+
+
+
\ No newline at end of file
diff --git a/Form1.cs b/Form1.cs
index c587fc0..fc7deb4 100644
--- a/Form1.cs
+++ b/Form1.cs
@@ -42,11 +42,11 @@ namespace CheckDownload
// 阿里云OSS访问密钥Secret
private const string OssAccessKeySecret = "7ClQns3wz6psmIp9T2OfuEn3tpzrCK";
// 123盘鉴权密钥
- private const string OneDriveAuthKey = "ZhwG3LxOtGJwM3ym";
+ private const string OneDriveAuthKey = "6SwdpWdSJuJRSh";
// 123盘UID
- private const string OneDriveUid = "1850250683";
+ private const string OneDriveUid = "1826795402";
// 123盘路径(不包含域名)- 修改此处即可同时生效于主备域名
- private const string OneDrivePath = "/1850250683/SuWin";
+ private const string OneDrivePath = "/1826795402/KeyAuth";
// 123盘主域名
private const string OneDriveMainDomain = "vip.123pan.cn";
// 123盘备用域名
@@ -75,6 +75,15 @@ namespace CheckDownload
// 基准目录路径(用于文件更新的目标目录)
private string _baseDirectory;
+ // 7z.dll 库文件路径
+ private readonly string _sevenZipDllPath;
+
+ // 应用程序名称
+ private readonly string _appName;
+
+ // 当前进程ID
+ private readonly int _currentProcessId;
+
// === 新增: 用于显示整体下载大小与速度 ===
private long _totalDownloadedBytes = 0; // 已下载总字节数
private DateTime _downloadStartTime; // 下载开始时间
@@ -88,9 +97,14 @@ namespace CheckDownload
public Update()
{
InitializeComponent();
+
+ // 设置 7z.dll 的路径为程序运行目录
+ _sevenZipDllPath = Path.Combine(Application.StartupPath, "7z.dll");
+
+ _appName = Assembly.GetExecutingAssembly().GetName().Name;
+ _currentProcessId = Process.GetCurrentProcess().Id;
_baseDirectory = Application.StartupPath;
ConfigureProgressBar();
- InitializeTempDirectory();
}
///
@@ -207,6 +221,7 @@ namespace CheckDownload
{
try
{
+ InitializeTempDirectory();
CleanupNewFiles();
UpdateStatus("下载在线MD5文件并读取...");
UpdateCount("");
@@ -296,7 +311,7 @@ namespace CheckDownload
if (_completedCount == 0 && orderedFileList.Count > 0)
{
- throw new Exception("所有文件下载失败。");
+ throw new Exception("UpdateFile: 所有文件下载失败。");
}
await VerifyAndSaveAllFiles();
@@ -314,8 +329,7 @@ namespace CheckDownload
}
catch (Exception ex)
{
- UpdateStatus("更新失败");
- MessageBox.Show($"更新失败:\n{ex.Message}", "Update Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ HandleError("文件更新主流程 (UpdateFile)", ex);
await Task.Delay(3000);
this.Close();
}
@@ -370,8 +384,7 @@ namespace CheckDownload
}
catch (Exception ex) when (ex is OssException || ex is JsonException)
{
- UpdateStatus($"读取在线MD5文件失败: {ex.Message}");
- return (null, null, null);
+ throw new Exception($"ReadOnlineMd5File: 读取或解析在线MD5文件 '{filePath}' 失败。", ex);
}
}
@@ -947,7 +960,9 @@ namespace CheckDownload
if (failedFiles.Count > 0)
{
- throw new Exception($"{failedFiles.Count}个文件校验失败");
+ string failedFileList = string.Join(", ", failedFiles.Take(3));
+ if (failedFiles.Count > 3) failedFileList += "...";
+ throw new Exception($"VerifyAndSaveAllFiles: {failedFiles.Count}个文件校验失败: {failedFileList}");
}
else
{
@@ -1043,7 +1058,7 @@ namespace CheckDownload
}
catch (Exception ex)
{
- UpdateStatus($"创建替换脚本时出错: {ex.Message}");
+ HandleError("创建文件替换脚本 (CreateReplaceScriptForAll)", ex);
}
}
@@ -1057,7 +1072,7 @@ namespace CheckDownload
_tempDirectory = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"Temp",
- "CheckDownload"
+ _appName
);
if (!Directory.Exists(_tempDirectory))
@@ -1067,7 +1082,7 @@ namespace CheckDownload
}
catch (Exception ex)
{
- UpdateStatus($"初始化临时目录失败: {ex.Message}");
+ throw new Exception("初始化临时目录 (InitializeTempDirectory)", ex);
}
}
@@ -1310,7 +1325,7 @@ namespace CheckDownload
string tempPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"Temp",
- "CheckDownload"
+ _appName
);
if (Directory.Exists(tempPath))
@@ -1547,22 +1562,17 @@ namespace CheckDownload
await Task.Run(() => {
try
{
- string sevenZipDllPath = Extract7zDll();
- if (string.IsNullOrEmpty(sevenZipDllPath))
- {
- throw new Exception("无法提取7z.dll,解压中止。");
- }
-
string extractionPath = Path.GetDirectoryName(sevenZipFile);
string tempExtractionDir = Path.Combine(_tempDirectory, Path.GetFileNameWithoutExtension(sevenZipFile) + "_temp");
-
+
if (Directory.Exists(tempExtractionDir))
{
Directory.Delete(tempExtractionDir, true);
}
Directory.CreateDirectory(tempExtractionDir);
- using (var archiveFile = new ArchiveFile(sevenZipFile, sevenZipDllPath))
+ // 使用 SevenZipExtractor 解压文件到临时目录
+ using (var archiveFile = new ArchiveFile(sevenZipFile, _sevenZipDllPath))
{
archiveFile.Extract(tempExtractionDir, true);
}
@@ -1586,17 +1596,10 @@ namespace CheckDownload
}
Directory.Delete(tempExtractionDir, true);
-
- UpdateStatus("为解压的程序设置管理员权限...");
- var exeFiles = Directory.GetFiles(extractionPath, "*.exe", SearchOption.AllDirectories);
- foreach (var exeFile in exeFiles)
- {
- SetRunAsAdminCompatibility(exeFile);
- }
}
catch (Exception ex)
{
- throw new Exception($"解压失败: {ex.Message}");
+ throw new Exception("DecompressTim7zAsync: 解压失败。", ex);
}
});
@@ -1606,8 +1609,7 @@ namespace CheckDownload
}
catch (Exception ex)
{
- UpdateStatus($"处理 tim.7z 时出错: {ex.Message}");
- await Task.Delay(3000);
+ throw new Exception("DecompressTim7zAsync: 处理 tim.7z 时出错。", ex);
}
}
@@ -1615,69 +1617,6 @@ namespace CheckDownload
/// 为指定程序路径在注册表中设置"以管理员身份运行"的兼容性标志。
///
/// 要设置的.exe文件的完整路径。
- private void SetRunAsAdminCompatibility(string exePath)
- {
- const string keyPath = @"Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers";
- try
- {
- using (RegistryKey key = Registry.CurrentUser.CreateSubKey(keyPath))
- {
- if (key != null)
- {
- key.SetValue(exePath, "~ RUNASADMIN");
- }
- else
- {
- UpdateStatus($"无法打开或创建注册表项: {keyPath}");
- }
- }
- }
- catch (Exception ex)
- {
- UpdateStatus($"设置管理员权限失败: {exePath} - {ex.Message}");
- }
- }
-
- ///
- /// 从嵌入的资源中提取与当前进程体系结构匹配的7z.dll到临时目录。
- ///
- /// 提取的7z.dll的路径,如果失败则返回null。
- private string Extract7zDll()
- {
- try
- {
- string dllName = Environment.Is64BitProcess ? "7z-x64.dll" : "7z.dll";
- string resourceName = $"CheckDownload.{dllName}";
- string dllPath = Path.Combine(_tempDirectory, "7z.dll");
-
- if (File.Exists(dllPath))
- {
- // 可以选择在这里添加对现有DLL版本的校验,但为简化,我们先直接返回
- return dllPath;
- }
-
- using (var resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
- {
- if (resourceStream == null)
- {
- UpdateStatus($"在嵌入资源中未找到 {dllName}。");
- return null;
- }
-
- using (var fileStream = new FileStream(dllPath, FileMode.Create, FileAccess.Write))
- {
- resourceStream.CopyTo(fileStream);
- }
- }
- return dllPath;
- }
- catch (Exception ex)
- {
- UpdateStatus($"提取7z.dll失败: {ex.Message}");
- return null;
- }
- }
-
// add helper to check db extension
private bool IsDatabaseFile(string relativePath)
{
@@ -1690,12 +1629,19 @@ namespace CheckDownload
try
{
string exeName = Path.GetFileNameWithoutExtension(exeRelativePath);
+ string targetExeDir = Path.GetDirectoryName(Path.Combine(_baseDirectory, exeRelativePath));
+
foreach (var proc in Process.GetProcessesByName(exeName))
{
+ if (proc.Id == _currentProcessId) continue;
try
{
- proc.Kill();
- proc.WaitForExit(5000);
+ string runningProcessDir = Path.GetDirectoryName(proc.MainModule.FileName);
+ if (string.Equals(runningProcessDir, targetExeDir, StringComparison.OrdinalIgnoreCase))
+ {
+ proc.Kill();
+ proc.WaitForExit(5000);
+ }
}
catch { }
}
@@ -1707,17 +1653,18 @@ namespace CheckDownload
{
try
{
- foreach (var proc in Process.GetProcesses())
+ foreach (var proc in Process.GetProcessesByName(baseName))
{
- if (string.Equals(proc.ProcessName, baseName, StringComparison.OrdinalIgnoreCase))
+ if (proc.Id == _currentProcessId) continue;
+ try
{
- try
+ if (proc.MainModule.FileName.StartsWith(_baseDirectory, StringComparison.OrdinalIgnoreCase))
{
proc.Kill();
proc.WaitForExit(5000);
}
- catch { }
}
+ catch { }
}
}
catch { }
@@ -1755,5 +1702,25 @@ namespace CheckDownload
_lastSpeedUpdateTime = now;
UpdateSize(sizeText);
}
+
+ ///
+ /// 统一处理并显示错误信息
+ ///
+ /// 要显示给用户的基本错误信息
+ /// 可选的异常对象,其消息将被附加
+ private void HandleError(string location, Exception ex = null)
+ {
+ UpdateStatus("更新失败");
+
+ // 递归查找最深层的 InnerException 以获取最根本的错误信息
+ var innermostException = ex;
+ while (innermostException?.InnerException != null)
+ {
+ innermostException = innermostException.InnerException;
+ }
+
+ string errorMessage = innermostException?.Message ?? ex?.Message ?? "发生未知错误。";
+ MessageBox.Show(errorMessage, "更新错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ }
}
}
\ No newline at end of file