我有一个用C#编写的WinForms应用程序。有一个部署项目,它创建一个setup.exe,并在其中设置版本号。
如何在运行时获取此版本号,以便将其写入日志或在“关于”框中显示?
我一直在使用以下代码,但它不适用于64位安装。
RegistryKey key = Registry.LocalMachine.OpenSubKey(
@"Software\Microsoft\Windows\CurrentVersion\Uninstall");
string[] subKeyNames = key.GetSubKeyNames();
foreach (string subKeyName in subKeyNames)
{
Microsoft.Win32.RegistryKey subKey2 = key.OpenSubKey(subKeyName);
if (ValueNameExists(subKey2.GetValueNames(), "DisplayName")
&& ValueNameExists(subKey2.GetValueNames(), "DisplayVersion"))
{
string name = subKey2.GetValue("DisplayName").ToString();
string version = subKey2.GetValue("DisplayVersion").ToString();
if(name == "MyAppName") return version;
}
subKey2.Close();
}
key.Close();
return "v?";
答案 0 :(得分:1)
你可以试试这个:
string registry_key = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
using (Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(registry_key))
{
foreach (string subkey_name in key.GetSubKeyNames())
{
using (Microsoft.Win32.RegistryKey subkey = key.OpenSubKey(subkey_name))
{
if (!object.ReferenceEquals(subkey.GetValue("DisplayName"), null))
{
string[] str = subkey.GetValueNames();
string SoftNames = Convert.ToString(subkey.GetValue("DisplayName"));
if (SoftNames == "MyAppName")
{
string Vendor_Publisher = Convert.ToString(subkey.GetValue("Publisher"));
string Version = Convert.ToString(subkey.GetValue("DisplayVersion"));
string InstallDate = FormatDateTime(subkey.GetValue("InstallDate"));
}
}
}
}
}
private static string FormatDateTime(object ObjInstallDate)
{
object FinalDate = DBNull.Value;
string strDate = Convert.ToString(ObjInstallDate);
DateTime dtm;
DateTime.TryParseExact(strDate, new string[] { "yyyyMMdd", "yyyy-MM-dd", "dd-MM-yyyy" },
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out dtm);
if (!String.IsNullOrEmpty(strDate))
{
FinalDate = dtm;
}
return FinalDate.ToString();
}
答案 1 :(得分:0)
如果您只想在应用程序的“关于”框中显示应用程序版本,可以按如下方式从静态属性中获取当前版本:
My.Application.Info.Version