c#获取文件版本号

获取 Windows 可执行文件(.exe/.dll)的版本号

在 .NET 中,可以通过 System.Diagnostics.FileVersionInfo 类读取 PE 文件(如 .exe.dll)的版本信息。

基本用法示例

using System.Diagnostics;

string filePath = @"C:\path\to\your\file.exe";
var versionInfo = FileVersionInfo.GetVersionInfo(filePath);

// 优先使用 ProductVersion(SAP 等企业软件通常将 ProductVersion 作为对外版本标识)
string version = versionInfo.ProductVersion?.Trim() 
                 ?? versionInfo.FileVersion?.Trim() 
                 ?? "Unknown";

## 关键属性说明

| 属性            | 含义                                       | 适用场景 |
|-----------------|--------------------------------------------|----------|
| `ProductVersion` | 产品版本号,由开发者在资源中定义,常用于对外发布版本标识 | 推荐优先使用,尤其在 SAP、Oracle 等企业软件中,此字段更贴近用户可见的版本 |
| `FileVersion`    | 文件本身的内部版本号,通常用于构建/编译跟踪         | 若 `ProductVersion` 为空或未设置,可作为备选 |

##
try
{
    var versionInfo = FileVersionInfo.GetVersionInfo(filePath);
    string version = versionInfo.ProductVersion?.Trim() 
                     ?? versionInfo.FileVersion?.Trim() 
                     ?? "Version not available";
}
catch (FileNotFoundException)
{
    // 文件不存在
}
catch (ArgumentException)
{
    // 路径格式无效
}
catch (Exception ex)
{
    // 其他异常(如无访问权限)
}
##
posted @ 2025-12-25 14:10  dd12138  阅读(25)  评论(0)    收藏  举报