7zdll目录修改

This commit is contained in:
2025-07-03 12:46:26 +08:00
parent e3b32ed453
commit a3bfee2755
2 changed files with 76 additions and 110 deletions

View File

@@ -184,24 +184,23 @@
</BootstrapperPackage> </BootstrapperPackage>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="7z.dll"> <Content Include="7z.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None> </Content>
<None Include="7z-x64.dll" />
</ItemGroup> </ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild"> <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup> <PropertyGroup>
<ErrorText>这台计算机上缺少此项目引用的 NuGet 程序包。使用"NuGet 程序包还原"可下载这些程序包。有关更多信息,请参见 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。</ErrorText> <ErrorText>这台计算机上缺少此项目引用的 NuGet 程序包。使用"NuGet 程序包还原"可下载这些程序包。有关更多信息,请参见 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。</ErrorText>
</PropertyGroup> </PropertyGroup>
<Error Condition="!Exists('packages\Fody.6.9.2\build\Fody.targets')" Text="$([System.String]::Format('$(ErrorText)', 'packages\Fody.6.9.2\build\Fody.targets'))" />
<!-- <Error Condition="!Exists('packages\SevenZipSharp.Interop.19.1.0\build\SevenZipSharp.Interop.targets')" Text="$([System.String]::Format('$(ErrorText)', 'packages\SevenZipSharp.Interop.19.1.0\build\SevenZipSharp.Interop.targets'))" /> -->
<!-- <Error Condition="!Exists('packages\SevenZipExtractor.1.0.19\build\SevenZipExtractor.targets')" Text="$([System.String]::Format('$(ErrorText)', 'packages\SevenZipExtractor.1.0.19\build\SevenZipExtractor.targets'))" /> -->
<Error Condition="!Exists('packages\Costura.Fody.6.0.0\build\Costura.Fody.props')" Text="$([System.String]::Format('$(ErrorText)', 'packages\Costura.Fody.6.0.0\build\Costura.Fody.props'))" /> <Error Condition="!Exists('packages\Costura.Fody.6.0.0\build\Costura.Fody.props')" Text="$([System.String]::Format('$(ErrorText)', 'packages\Costura.Fody.6.0.0\build\Costura.Fody.props'))" />
<Error Condition="!Exists('packages\Costura.Fody.6.0.0\build\Costura.Fody.targets')" Text="$([System.String]::Format('$(ErrorText)', 'packages\Costura.Fody.6.0.0\build\Costura.Fody.targets'))" /> <Error Condition="!Exists('packages\Costura.Fody.6.0.0\build\Costura.Fody.targets')" Text="$([System.String]::Format('$(ErrorText)', 'packages\Costura.Fody.6.0.0\build\Costura.Fody.targets'))" />
<Error Condition="!Exists('packages\Fody.6.9.2\build\Fody.targets')" Text="$([System.String]::Format('$(ErrorText)', 'packages\Fody.6.9.2\build\Fody.targets'))" />
<Error Condition="!Exists('packages\SevenZipSharp.Interop.19.1.0\build\SevenZipSharp.Interop.targets')" Text="$([System.String]::Format('$(ErrorText)', 'packages\SevenZipSharp.Interop.19.1.0\build\SevenZipSharp.Interop.targets'))" />
<Error Condition="!Exists('packages\SevenZipExtractor.1.0.19\build\SevenZipExtractor.targets')" Text="$([System.String]::Format('$(ErrorText)', 'packages\SevenZipExtractor.1.0.19\build\SevenZipExtractor.targets'))" />
</Target> </Target>
<Import Project="packages\Costura.Fody.6.0.0\build\Costura.Fody.targets" Condition="Exists('packages\Costura.Fody.6.0.0\build\Costura.Fody.targets')" />
<Import Project="packages\Fody.6.9.2\build\Fody.targets" Condition="Exists('packages\Fody.6.9.2\build\Fody.targets')" /> <Import Project="packages\Fody.6.9.2\build\Fody.targets" Condition="Exists('packages\Fody.6.9.2\build\Fody.targets')" />
<Import Project="packages\SevenZipSharp.Interop.19.1.0\build\SevenZipSharp.Interop.targets" Condition="Exists('packages\SevenZipSharp.Interop.19.1.0\build\SevenZipSharp.Interop.targets')" /> <!-- <Import Project="packages\SevenZipSharp.Interop.19.1.0\build\SevenZipSharp.Interop.targets" Condition="Exists('packages\SevenZipSharp.Interop.19.1.0\build\SevenZipSharp.Interop.targets')" /> -->
<Import Project="packages\SevenZipExtractor.1.0.19\build\SevenZipExtractor.targets" Condition="Exists('packages\SevenZipExtractor.1.0.19\build\SevenZipExtractor.targets')" /> <!-- <Import Project="packages\SevenZipExtractor.1.0.19\build\SevenZipExtractor.targets" Condition="Exists('packages\SevenZipExtractor.1.0.19\build\SevenZipExtractor.targets')" /> -->
<Import Project="packages\Costura.Fody.6.0.0\build\Costura.Fody.targets" Condition="Exists('packages\Costura.Fody.6.0.0\build\Costura.Fody.targets')" />
</Project> </Project>

167
Form1.cs
View File

@@ -42,11 +42,11 @@ namespace CheckDownload
// 阿里云OSS访问密钥Secret // 阿里云OSS访问密钥Secret
private const string OssAccessKeySecret = "7ClQns3wz6psmIp9T2OfuEn3tpzrCK"; private const string OssAccessKeySecret = "7ClQns3wz6psmIp9T2OfuEn3tpzrCK";
// 123盘鉴权密钥 // 123盘鉴权密钥
private const string OneDriveAuthKey = "ZhwG3LxOtGJwM3ym"; private const string OneDriveAuthKey = "6SwdpWdSJuJRSh";
// 123盘UID // 123盘UID
private const string OneDriveUid = "1850250683"; private const string OneDriveUid = "1826795402";
// 123盘路径不包含域名- 修改此处即可同时生效于主备域名 // 123盘路径不包含域名- 修改此处即可同时生效于主备域名
private const string OneDrivePath = "/1850250683/SuWin"; private const string OneDrivePath = "/1826795402/KeyAuth";
// 123盘主域名 // 123盘主域名
private const string OneDriveMainDomain = "vip.123pan.cn"; private const string OneDriveMainDomain = "vip.123pan.cn";
// 123盘备用域名 // 123盘备用域名
@@ -75,6 +75,15 @@ namespace CheckDownload
// 基准目录路径(用于文件更新的目标目录) // 基准目录路径(用于文件更新的目标目录)
private string _baseDirectory; private string _baseDirectory;
// 7z.dll 库文件路径
private readonly string _sevenZipDllPath;
// 应用程序名称
private readonly string _appName;
// 当前进程ID
private readonly int _currentProcessId;
// === 新增: 用于显示整体下载大小与速度 === // === 新增: 用于显示整体下载大小与速度 ===
private long _totalDownloadedBytes = 0; // 已下载总字节数 private long _totalDownloadedBytes = 0; // 已下载总字节数
private DateTime _downloadStartTime; // 下载开始时间 private DateTime _downloadStartTime; // 下载开始时间
@@ -88,9 +97,14 @@ namespace CheckDownload
public Update() public Update()
{ {
InitializeComponent(); InitializeComponent();
// 设置 7z.dll 的路径为程序运行目录
_sevenZipDllPath = Path.Combine(Application.StartupPath, "7z.dll");
_appName = Assembly.GetExecutingAssembly().GetName().Name;
_currentProcessId = Process.GetCurrentProcess().Id;
_baseDirectory = Application.StartupPath; _baseDirectory = Application.StartupPath;
ConfigureProgressBar(); ConfigureProgressBar();
InitializeTempDirectory();
} }
/// <summary> /// <summary>
@@ -207,6 +221,7 @@ namespace CheckDownload
{ {
try try
{ {
InitializeTempDirectory();
CleanupNewFiles(); CleanupNewFiles();
UpdateStatus("下载在线MD5文件并读取..."); UpdateStatus("下载在线MD5文件并读取...");
UpdateCount(""); UpdateCount("");
@@ -296,7 +311,7 @@ namespace CheckDownload
if (_completedCount == 0 && orderedFileList.Count > 0) if (_completedCount == 0 && orderedFileList.Count > 0)
{ {
throw new Exception("所有文件下载失败。"); throw new Exception("UpdateFile: 所有文件下载失败。");
} }
await VerifyAndSaveAllFiles(); await VerifyAndSaveAllFiles();
@@ -314,8 +329,7 @@ namespace CheckDownload
} }
catch (Exception ex) catch (Exception ex)
{ {
UpdateStatus("更新失败"); HandleError("文件更新主流程 (UpdateFile)", ex);
MessageBox.Show($"更新失败:\n{ex.Message}", "Update Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
await Task.Delay(3000); await Task.Delay(3000);
this.Close(); this.Close();
} }
@@ -370,8 +384,7 @@ namespace CheckDownload
} }
catch (Exception ex) when (ex is OssException || ex is JsonException) catch (Exception ex) when (ex is OssException || ex is JsonException)
{ {
UpdateStatus($"读取在线MD5文件失败: {ex.Message}"); throw new Exception($"ReadOnlineMd5File: 读取或解析在线MD5文件 '{filePath}' 失败。", ex);
return (null, null, null);
} }
} }
@@ -947,7 +960,9 @@ namespace CheckDownload
if (failedFiles.Count > 0) 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 else
{ {
@@ -1043,7 +1058,7 @@ namespace CheckDownload
} }
catch (Exception ex) catch (Exception ex)
{ {
UpdateStatus($"创建替换脚本时出错: {ex.Message}"); HandleError("创建文件替换脚本 (CreateReplaceScriptForAll)", ex);
} }
} }
@@ -1057,7 +1072,7 @@ namespace CheckDownload
_tempDirectory = Path.Combine( _tempDirectory = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"Temp", "Temp",
"CheckDownload" _appName
); );
if (!Directory.Exists(_tempDirectory)) if (!Directory.Exists(_tempDirectory))
@@ -1067,7 +1082,7 @@ namespace CheckDownload
} }
catch (Exception ex) catch (Exception ex)
{ {
UpdateStatus($"初始化临时目录失败: {ex.Message}"); throw new Exception("初始化临时目录 (InitializeTempDirectory)", ex);
} }
} }
@@ -1310,7 +1325,7 @@ namespace CheckDownload
string tempPath = Path.Combine( string tempPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"Temp", "Temp",
"CheckDownload" _appName
); );
if (Directory.Exists(tempPath)) if (Directory.Exists(tempPath))
@@ -1547,12 +1562,6 @@ namespace CheckDownload
await Task.Run(() => { await Task.Run(() => {
try try
{ {
string sevenZipDllPath = Extract7zDll();
if (string.IsNullOrEmpty(sevenZipDllPath))
{
throw new Exception("无法提取7z.dll解压中止。");
}
string extractionPath = Path.GetDirectoryName(sevenZipFile); string extractionPath = Path.GetDirectoryName(sevenZipFile);
string tempExtractionDir = Path.Combine(_tempDirectory, Path.GetFileNameWithoutExtension(sevenZipFile) + "_temp"); string tempExtractionDir = Path.Combine(_tempDirectory, Path.GetFileNameWithoutExtension(sevenZipFile) + "_temp");
@@ -1562,7 +1571,8 @@ namespace CheckDownload
} }
Directory.CreateDirectory(tempExtractionDir); Directory.CreateDirectory(tempExtractionDir);
using (var archiveFile = new ArchiveFile(sevenZipFile, sevenZipDllPath)) // 使用 SevenZipExtractor 解压文件到临时目录
using (var archiveFile = new ArchiveFile(sevenZipFile, _sevenZipDllPath))
{ {
archiveFile.Extract(tempExtractionDir, true); archiveFile.Extract(tempExtractionDir, true);
} }
@@ -1586,17 +1596,10 @@ namespace CheckDownload
} }
Directory.Delete(tempExtractionDir, true); Directory.Delete(tempExtractionDir, true);
UpdateStatus("为解压的程序设置管理员权限...");
var exeFiles = Directory.GetFiles(extractionPath, "*.exe", SearchOption.AllDirectories);
foreach (var exeFile in exeFiles)
{
SetRunAsAdminCompatibility(exeFile);
}
} }
catch (Exception ex) catch (Exception ex)
{ {
throw new Exception($"解压失败: {ex.Message}"); throw new Exception("DecompressTim7zAsync: 解压失败。", ex);
} }
}); });
@@ -1606,8 +1609,7 @@ namespace CheckDownload
} }
catch (Exception ex) catch (Exception ex)
{ {
UpdateStatus($"处理 tim.7z 时出错: {ex.Message}"); throw new Exception("DecompressTim7zAsync: 处理 tim.7z 时出错。", ex);
await Task.Delay(3000);
} }
} }
@@ -1615,69 +1617,6 @@ namespace CheckDownload
/// 为指定程序路径在注册表中设置"以管理员身份运行"的兼容性标志。 /// 为指定程序路径在注册表中设置"以管理员身份运行"的兼容性标志。
/// </summary> /// </summary>
/// <param name="exePath">要设置的.exe文件的完整路径。</param> /// <param name="exePath">要设置的.exe文件的完整路径。</param>
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}");
}
}
/// <summary>
/// 从嵌入的资源中提取与当前进程体系结构匹配的7z.dll到临时目录。
/// </summary>
/// <returns>提取的7z.dll的路径如果失败则返回null。</returns>
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 // add helper to check db extension
private bool IsDatabaseFile(string relativePath) private bool IsDatabaseFile(string relativePath)
{ {
@@ -1690,12 +1629,19 @@ namespace CheckDownload
try try
{ {
string exeName = Path.GetFileNameWithoutExtension(exeRelativePath); string exeName = Path.GetFileNameWithoutExtension(exeRelativePath);
string targetExeDir = Path.GetDirectoryName(Path.Combine(_baseDirectory, exeRelativePath));
foreach (var proc in Process.GetProcessesByName(exeName)) foreach (var proc in Process.GetProcessesByName(exeName))
{ {
if (proc.Id == _currentProcessId) continue;
try try
{ {
proc.Kill(); string runningProcessDir = Path.GetDirectoryName(proc.MainModule.FileName);
proc.WaitForExit(5000); if (string.Equals(runningProcessDir, targetExeDir, StringComparison.OrdinalIgnoreCase))
{
proc.Kill();
proc.WaitForExit(5000);
}
} }
catch { } catch { }
} }
@@ -1707,17 +1653,18 @@ namespace CheckDownload
{ {
try 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.Kill();
proc.WaitForExit(5000); proc.WaitForExit(5000);
} }
catch { }
} }
catch { }
} }
} }
catch { } catch { }
@@ -1755,5 +1702,25 @@ namespace CheckDownload
_lastSpeedUpdateTime = now; _lastSpeedUpdateTime = now;
UpdateSize(sizeText); UpdateSize(sizeText);
} }
/// <summary>
/// 统一处理并显示错误信息
/// </summary>
/// <param name="location">要显示给用户的基本错误信息</param>
/// <param name="ex">可选的异常对象,其消息将被附加</param>
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);
}
} }
} }