Modify Program Version Number through Registry in C#

2023年10月23日 1920点热度 0人点赞 0条评论
内容目录

file

After installing the software, it requires an update. Once the update file is complete, the version number of the program in the registry also needs to be modified.

After the software is installed, it will be written into the registry.

file

Therefore, it is sufficient to modify the DisplayVersion in the registry. Different programs may also require modifications to other attributes, such as Version and DisplayName.

Modifying the registry may require administrative privileges, depending on whether the software is installed for all users or just for the current user.

Each program's KEY is different, and you need to assemble it on your own.

file


		static void Main(string[] args)
		{
			string code = "4444-4444-4444-4444-4444";
			SearchRegistryKeys(code, new Version(1, 6, 6, 6));
			Console.ReadKey();
		}

		[SupportedOSPlatform("windows")]
		static bool SearchRegistryKeys(string guid, Version newVersion)
		{
			const string LocalMachine = "SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{0}";
			const string CurrentUser = "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{0}";
			try
			{
				// Open the specified subkey
				RegistryKey? baseKey = Registry.LocalMachine.OpenSubKey(string.Format(LocalMachine, guid), writable: true);
				if (baseKey == null)
				{
					baseKey = Registry.CurrentUser.OpenSubKey(string.Format(CurrentUser, guid), writable: true);
				}

				if (baseKey == null) return false;

				// Get all subkey names
				string[] kvs = baseKey.GetValueNames();
				if (kvs.Any(x => x == "DisplayVersion"))
				{
					var version = baseKey.GetValue("DisplayVersion")?.ToString();
					if (version == null) return false;
					baseKey.SetValue("DisplayVersion", newVersion.ToString());
					var name = baseKey.GetValue("DisplayName")?.ToString();
					if (name == null) return false;
					baseKey.SetValue("DisplayName", name.Replace(version, newVersion.ToString()));
				}
				baseKey.Dispose();
				return true;
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex);
				return false;
			}
		}

痴者工良

高级程序员劝退师

文章评论