I'm trying to add a registry key through my code on the startup of the program. I'm completely new to this and I don't know how to (and couldn't search for) but I have tried with this code:
RegistryKey HTML5Key = Registry.LocalMachine.OpenSubKey("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer\\MAIN\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);
if (HTML5Key != null)
{
HTML5Key.SetValue("mybrowser.exe", "270f", RegistryValueKind.DWord);
HTML5Key.Close();
}
But it simply does nothing. What am I doing wrong? I have admin rights. I have tried to debug it but I can't even get inside the if bracket.
You use OpenSubKey to open key in registry, so if specified key is not exist in registry it will return null. That is why your code is not working. Check whether sub key exist or not and then open it for writting.
One more mistake in your code you want to open HKEY_CURRENT_USER sub key so write code as follows
Registry.CurrentUser.OpenSubKey("SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer\\MAIN\\FeatureControl\\FEATURE_BROWSER_EMULATION", true)
You can use below code for write the value in registry.
private string _subKey = "Microsoft\\Internet Explorer\\MAIN\\FeatureControl\\FEATURE_BROWSER_EMULATION";
private string SubKey
{
get { return _subKey; }
set { _subKey = value; }
}
private RegistryKey _baseRegistryKey = Registry.LocalMachine;
private RegistryKey BaseRegistryKey
{
get { return _baseRegistryKey; }
set { _baseRegistryKey = value; }
}
private bool WriteDbToRegistry(string keyName, object value)
{
try
{
var rk = BaseRegistryKey;
var sk1 = rk.CreateSubKey(SubKey);
if(sk1 != null) sk1.SetValue(keyName.ToUpper(), value);
return true;
}
catch(Exception e)
{
MessageBox.Show("Please run your App as Administrator.", "Administrator");
return false;
}
}
bool results = WriteDbToRegistry("Keyname", "2710");
and get value from registry..
public string GetRegistryValue()
{
var rk = BaseRegistryKey;
var sk1 = rk.OpenSubKey(SubKey);
try
{
return (string)sk1.GetValue("Keyname");
}
catch (Exception e)
{
MessageBox.Show(e.Message, "some message");
return null;
}
}
I put this together with minor changes to the code previously given by JasRaj to create the registry entry:
private string _subKey = "SOFTWARE\\Microsoft\\Internet Explorer\\MAIN\\FeatureControl\\FEATURE_BROWSER_EMULATION";
private string SubKey
{
get { return _subKey; }
set { _subKey = value; }
}
private RegistryKey _baseRegistryKey = Registry.LocalMachine;
private RegistryKey BaseRegistryKey
{
get { return _baseRegistryKey; }
set { _baseRegistryKey = value; }
}
private bool WriteDbToRegistry(string keyName, object value)
{
try
{
var rk = BaseRegistryKey;
var sk1 = rk.OpenSubKey(SubKey,true); //true is required for making it writable
if (sk1 != null)
{
sk1.SetValue(keyName, value,RegistryValueKind.DWord); //dword,qword
rk.Close();
sk1.Close();
return true;
}
else
{
rk.Close();
sk1.Close();
return false;
}
}
catch(Exception e)
{
MessageBox.Show(e.Message);
return false;
}
}
public string GetRegistryValue(string keyname)
{
var rk = BaseRegistryKey;
var sk1 = rk.OpenSubKey(SubKey);
try
{
return sk1.GetValue(keyname).ToString();
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Error");
return null;
}
}
There are two problems with your code:
You likely don't have permissions to write to HKEY_LOCAL_MACHINE
You are not writing to the right location and an invalid value is used
Your problem is that you are writing to HKEY_LOCAL_MACHINE and you most likely don't have permissions to write there under a normal user account. Unless you are an Administrator and running under elevated rights you can't write there. However, for what you are trying to do luckily you don't need to write the HKLM, but you can write to the HKCU registry which is allowed.
Also the "270F" should be a number not a string so 0x270F without quotes should be used.
The following code is what I use in one of my applications to set browser emulation:
using (var rk = Registry.CurrentUser.OpenSubKey(#"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION",true))
{
dynamic value = rk.GetValue("MarkdownMonster.exe");
if (value == null)
rk.SetValue(exename, (uint) 11001, RegistryValueKind.DWord);
}
Related
I've created a service, which "locks" the desktop background, so you can't change it. In general, the service compares the current wallpaper with the one I want to be the new wallpaper. If it's not the same, it gets overwritten. This is my OnTimer()-Method, which gets executed every 2 seconds:
private void OnTimer(object sender, ElapsedEventArgs e)
{
if (!File.Exists("C:/Program Files/image.jpg"))
{
Assembly myAssembly = Assembly.GetExecutingAssembly();
Stream s = myAssembly.GetManifestResourceStream("MsService.Gandalf.jpg"); ;
byte[] b;
using (BinaryReader br = new BinaryReader(s))
{
b = br.ReadBytes((int)s.Length);
}
while (true)
{
try
{
File.WriteAllBytes("C:/Program Files/image.jpg", b);
break;
}
catch (Exception)
{
//stuff
}
}
}
//{path} is %Appdata%
if (!FileEquals($"{path}\\Microsoft\\Windows\\Themes\\TranscodedWallpaper", "C:/Program Files/image.jpg"))
{
byte[] file = File.ReadAllBytes("C:/Program Files/image.jpg");
while (true)
{
try
{
File.WriteAllBytes($"{path}\\Microsoft\\Windows\\Themes\\TranscodedWallpaper", file);
break;
}
catch (Exception)
{
//stuff
}
}
}
}
That's the FileEquals Method:
static bool FileEquals(string path1, string path2)
{
byte[] file1 = File.ReadAllBytes(path1);
byte[] file2 = File.ReadAllBytes(path2);
if (file1.Length == file2.Length)
{
for (int i = 0; i < file1.Length; i++)
{
if (file1[i] != file2[i])
{
return false;
}
}
return true;
}
return false;
}
When I start the service, It only changes the wallpaper if I change it actively, even if it already is another one that the one I want it to be, and only once. The service outputs no error when debugging, and the service doesn't crash. Also when I change the wallpaper, the breakpoints in the if(!File.Equals(...)) gets triggered. Virus scanner isn't alerting anything too. Why doesn't it work anyway?
I'm currently working on a installer kind of program. It has a system check page where I check if all the requerments are met or not. One requirement is the availability of BitLocker.
Currently I check for BitLocker by trying to create an instance of Win32_EncryptableVolume and then check if an exception is thrown or not.
But I wonder if there is a more elegant way.
My method currently looks basicaly like this:
public static bool IsBitlockerAvaliable()
{
try
{
var path = new ManagementPath
{
NamespacePath = #"\ROOT\CIMV2\Security\MicrosoftVolumeEncryption",
ClassName = "Win32_EncryptableVolume"
};
using (var wmi_class = new ManagementClass(path))
{
foreach (var o in wmi_class.GetInstances())
{
var vol = (ManagementObject) o;
if (vol == null)
throw new Exception("Vol is null");
Debug.WriteLine(vol);
}
}
return true;
}
catch (ManagementException e)
{
// No Admin rights is a different issue
if (e.ErrorCode == ManagementStatus.AccessDenied)
{
throw new AccessViolationException();
}
return false;
}
catch (Exception e)
{
return false;
}
}
Primarily am new to Developing.
I have Built a Setup File for my c# web Application using VS 2017. Am Going to Deploy my Setup in client Computer with Expiry Date which will be stored in registry. My setup can work in offline. But i want to collect/gather Client data weekly once. So What all i want is , let my client to use my setup without internet for one week. after that my setup have to become expired. Then he/she must connect with internet to extend an expiry date for Next one week. Kindly Help Me to achieve this. Thanks in advance
First of all create new form for read/write/check registry for check registration date and check with current date and add that for main form (first opening form, for this you can change form name in program.cs) , also you can add method in current main form and run that method in load events, after check you can chose between start program or show dialog for connect and extend or etc..
small code :
public partial class Reg_Form : Form
{
private string Reg_path = "Software\\MySampleProgram";
private string Reg_key = "Expire";
public Reg_Form()
{
InitializeComponent();
check_expire_date();
}
private void check_expire_date()
{
bool exists_key = check_reg();
if (!exists_key)
{
//first use, so we need to write expire date
bool is_write = write_reg();
if (!is_write)
{
MessageBox.Show("Run program as administrator and try again.");
this.Close();
}
}
var dt = read_reg_val();
if (dt != null)
{
DateTime current_date = DateTime.UtcNow;
DateTime reg_date = DateTime.UtcNow;
DateTime.TryParse(dt, out reg_date);
var res = (current_date - reg_date).TotalDays;
if (res < 7)
{
Main_Form frm = new Main_Form();
this.Hide();
frm.Show();
}
else
{
MessageBox.Show("Please connect to internet for extend time !");
//do any other work.....
}
}
else
{
MessageBox.Show("Error, try again !");
this.Close();
}
}
private bool write_reg()
{
try
{
Microsoft.Win32.RegistryKey key;
key = Microsoft.Win32.Registry.LocalMachine.CreateSubKey(Reg_path);
key.SetValue(Reg_key, DateTime.UtcNow.ToShortDateString());
key.Close();
return true;
}
catch
{
return false;
}
}
private bool check_reg()
{
try
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(Reg_path);
if (key != null)
{
Object o = key.GetValue(Reg_key);
if (o != null)
{
return true;
}
}
}
catch
{
return false;
}
return false;
}
private string read_reg_val()
{
try
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(Reg_path);
if (key != null)
{
Object o = key.GetValue(Reg_key);
if (o != null)
{
string res = o as String;
DateTime dt = DateTime.Now;
bool ok_date = DateTime.TryParse(res, out dt);
if (ok_date)
{
return res;
}
else
{
//changed value by user or hacked !
DateTime today = DateTime.UtcNow;
DateTime sevenDaysEarlier = today.AddDays(-8);
return sevenDaysEarlier.ToShortDateString();
}
}
}
}
catch
{
return null;
}
return null;
}
}
Note : this is note perfect, user can change the time & date on PC Or if can find registry can change and bypass expiry date, however it's good sample for you.
if problem solved, so please don't forget to mark answer as accepted/solved.
So in my registry I have the entry under "LocalMachine\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\" called "COMODO Internet Security" which is my firewall. Now what i'd like to know is how can i get the registry to check if that entry exists? If it does do this if not then do that. I know how to check if the subkey "Run" exists but not the entry for "COMODO Internet Security", this is the code I was using to get if the subkey exists.
using (RegistryKey Key = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\Run\"))
if (Key != null)
{
MessageBox.Show("found");
}
else
{
MessageBox.Show("not found");
}
If you're looking for a value under a subkey, (is that what you mean by "entry"?) you can use RegistryKey.GetValue(string). This will return the value if it exists, and null if it doesn't.
For example:
using (RegistryKey Key = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\Run\"))
if (Key != null)
{
string val = Key.GetValue("COMODO Internet Security");
if (val == null)
{
MessageBox.Show("value not found");
}
else
{
// use the value
}
}
else
{
MessageBox.Show("key not found");
}
Try this:
using (RegistryKey Key = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\Run\COMODO Internet Security"))
{
if (Key != null)
MessageBox.Show("found");
else
MessageBox.Show("not found");
}
The following link should clarify this:
How to check if a registry key / subkey already exists
Sample code:
using Microsoft.Win32;
RegistryKey rk = Registry.LocalMachine.OpenSubKey("Software\\Geekpedia\\Test");
if(rk != null)
{
// It's there
}
else
{
// It's not there
}
I ran into an issue recently where I was trying to grab subkeys in a registry entry, but the problem was that since I was iterating over every registry key in that section of the registry, sometimes values would not have the subkey I was looking for, and I would get a null reference exception when trying to evaluate the subkey's value.
So, very similar to what some other answers provided, this is what I ended up going with:
string subkeyValue = null;
var subKeyCheck = subkey.GetValue("SubKeyName");
if(subKeyCheck != null)
{
subkeyValue = subkey.GetValue("SubKeyName").ToString();
}
So depending on what subkey value you're looking for, just swap it out for "SubKeyName" and this should do the trick.
My code
private void button2_Click(object sender, EventArgs e)
{
string HKCUval = textBox1.Text;
RegistryKey HKCU = Registry.CurrentUser;
//Checks if HKCUval exist.
try {
HKCU.DeleteSubKey(HKCUval); //if exist.
}
catch (Exception)
{
MessageBox.Show(HKCUval + " Does not exist"); //if does not exist.
}
}
Hope it helps.
I am trying to Configure my IIS programmatically following the steps on this
msdn guide
the only difference i made was switching to winforms instead of console..
and variables instead of function parameters.
however the code throws an exception when i try to set the singleproperty value...
here is my code..
string metabasePath = "IIS://localhost/W3SVC/1234", propertyName = "ServerBindings";
object newValue = " :8080:";
try
{
DirectoryEntry path = new DirectoryEntry(metabasePath);
//when i try to retrieve the old value,it returns a null
PropertyValueCollection propValues = path.Properties[propertyName];
MessageBox.Show("7");
//the code throws an exception after messagebox,
//kinda old school debuging
path.Properties[propertyName][0] = newValue;
path.CommitChanges();
lblerror.Text = "Done";
}
catch (Exception ex)
{
if ("HRESULT 0x80005006" == ex.Message)
lblerror.Text = " Property does not exist at ";
else
lblerror.Text = "Failed in SetSingleProperty "+ ex.Message.ToString();
}
The following 'helper' methods (SetServerBinding and RemoveServerBinding) should be of use:
static void Main(string[] args)
{
using(DirectoryEntry site = new DirectoryEntry("IIS://Localhost/W3SVC/1234"))
{
SetServerBinding(":8080:", site);
RemoveServerBinding(":8080:", site);
RemoveServerBinding("172.16.4.99:8087:somesite.com", site);
SetServerBinding("172.16.4.99:8087:somesite.com", site);
}
}
public static void SetServerBinding(string binding, DirectoryEntry site)
{
if(site.Properties["ServerBindings"].Contains(binding))
{
site.Properties["ServerBindings"].Remove(binding);
return;
}
site.Properties["ServerBindings"].Add(binding);
site.CommitChanges();
}
public static void RemoveServerBinding(string binding, DirectoryEntry site)
{
if (site.Properties["ServerBindings"].Contains(binding))
{
site.Properties["ServerBindings"].Remove(binding);
}
site.CommitChanges();
}