我正在使用以下代码System.Deployment
返回我的 .NET 3.5 C# 应用程序的 ClickOnce 版本:
public string version
{
get
{
System.Reflection.Assembly _assemblyInfo = System.Reflection.Assembly.GetExecutingAssembly();
string ourVersion = string.Empty;
if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
{
ourVersion = System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString();
}
else
{
if (_assemblyInfo != null)
{
ourVersion = _assemblyInfo.GetName().Version.ToString();
}
}
return ourVersion;
}
}
如果我正常启动应用程序(例如从“开始”菜单),则该值始终会正确返回。但是,如果我使用注册表项在 Windows 中自动启动应用程序,则应用程序将返回默认的硬编码值 1.0.0.0。
如果我关闭自动启动的应用程序并手动重新打开它,它会再次返回正确的 ClickOnce 版本号。
关于为什么会这样的任何想法吗?这是我用来设置注册表项的代码:
string keyName = "MyApp";
string assemblyLocation = Assembly.GetExecutingAssembly().Location;
Util.SetAutoStart(keyName, assemblyLocation);
And
public class Util
{
private const string RUN_LOCATION = @"Software\Microsoft\Windows\CurrentVersion\Run";
/// <summary>
/// Sets the autostart value for the assembly.
/// </summary>
/// <param name="keyName">Registry Key Name</param>
/// <param name="assemblyLocation">Assembly location (e.g. Assembly.GetExecutingAssembly().Location)</param>
public static void SetAutoStart(string keyName, string assemblyLocation)
{
RegistryKey key = Registry.CurrentUser.CreateSubKey(RUN_LOCATION);
key.SetValue(keyName, assemblyLocation);
}
/// <summary>
/// Returns whether auto start is enabled.
/// </summary>
/// <param name="keyName">Registry Key Name</param>
/// <param name="assemblyLocation">Assembly location (e.g. Assembly.GetExecutingAssembly().Location)</param>
public static bool IsAutoStartEnabled(string keyName, string assemblyLocation)
{
RegistryKey key = Registry.CurrentUser.OpenSubKey(RUN_LOCATION);
if (key == null)
return false;
string value = (string)key.GetValue(keyName);
if (value == null)
return false;
return (value == assemblyLocation);
}
/// <summary>
/// Unsets the autostart value for the assembly.
/// </summary>
/// <param name="keyName">Registry Key Name</param>
public static void UnSetAutoStart(string keyName)
{
RegistryKey key = Registry.CurrentUser.CreateSubKey(RUN_LOCATION);
key.DeleteValue(keyName);
}
}