The following code is not working for me:
public bool createRegistry()
{
if (!registryExists())
{
Microsoft.Win32.Registry.LocalMachine.CreateSubKey("Software\\xelo\\");
Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\\xelo").SetValue("hostname", (string)hostname, Microsoft.Win32.RegistryValueKind.String);
return true;
}
else
{
return updateRegistry();
}
}
Exception:
System.UnauthorizedAccessException | "Cannot write to the registry
key"
Non-admin and unelevated admin users don't have rights to modify the HKEY_LOCAL_MACHINE key. Run the program 'as administrator'.
Below code to create key in the registry.
Microsoft.Win32.RegistryKey key;
key = Microsoft.Win32.Registry.LocalMachine.CreateSubKey("Software\\Wow6432Node\\Names");
key.SetValue("Name", "Isabella");
key.Close();
Even when admin I don't think you can create new keys off LocalMachine. Make sure that you do
Registry.LocalMachine.CreateSubKey(#"SOFTWARE\YourCompanyName\SomeNewKey");
and not
Registry.LocalMachine.CreateSubKey("SomeNewKey");
Well you've got your answer already - I'm guessing you're running on Vista or Windows 7 (or Server 2008) and the process/user running the app doesn't have rights/permission to modify the registry.
So its not a code problem as such but a systems admin one. Build the app and run as administrator and see if that works.
Set the Premission Check bit to true...
Microsoft.Win32.Registry.LocalMachine.CreateSubKey("Software\\xelo\\", true);
:)
Related
I have created an application(windows) compiled with .NET 4.6.1 and used the FolderBrowserDialog object. When a button is pressed I execute this code:
FolderBrowserDialog folderbrowserdialog = new FolderBrowserDialog();
folderbrowserdialog.Description = "Custom Description";
if (folderbrowserdialog.ShowDialog() == DialogResult.OK)
{
filePath = folderbrowserdialog.SelectedPath ;
}
what i get from the folderbrowserdialog(like foto)
however ,the folder browserdialog is not showing the networks shared folder(that the purpose of my app) otherewise just the pc folders.
but what i want to get it is the network shared folders which could i also access from windows 10 like foto here:
notes to be marked:
i could not use the open file dialog cause i need the folder location.
i desgined the Appto be opened just like admin by adding manisfest so the app is always starting like admin.
the app should be comptiable with windows 10,7
note i know that i could try setting this registry option (could be broken in Win10):
HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Windows/CurrentVersion/Policies/System
EnableLinkedConnections=1
but it does not make a sense to add this registry by every customer PC
so is there any tipps to show the network shared folders in FolderBrowserDialog ?
Finally after reading many topics i found that the only solution is to add a Registry key programmatically so here how to add specfic C# Registry Subkey with dword value:
i wrote a method wich could all use it
just to let you know after using it you have to restart the device after it ,it will work ;)
public void ConfigureWindowsRegistry()
{
RegistryKey localMachine = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64); //here you specify where exactly you want your entry
var reg = localMachine.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", true);
if (reg == null)
{
reg = localMachine.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", true);
}
if (reg.GetValue("EnableLinkedConnections") == null)
{
reg.SetValue("EnableLinkedConnections", "1", RegistryValueKind.DWord);
MessageBox.Show(
"Your configuration is now created,you have to restart your device to let app work perfektly");
}
}
I had the same issue. The reason of the problem: I was using as an Administrator. The mapped drives are related to the user, so I tried to use as an normal user and I could see the mapped drives.
I want a .bat file to run whenever the machine starts (or alternatively whenever a user is signed in)
For this I've made this piece of code:
string subKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
RegistryKey key;
if (ClientSystem.Is64BitOperatingSystem)
{
key = RegistryKey.OpenBaseKey(
RegistryHive.LocalMachine,
RegistryView.Registry64
).OpenSubKey(subKey);
}
else
{
key = Registry.LocalMachine.OpenSubKey(subKey, true);
}
key.SetValue("websocket", #"c:\websocket\run.bat"); // error here
when running this I get an error telling me that I don't have permission change the file.
As #Tolanj mentions it might be an idea to add the actual error message:
Der kan ikke skrives til registreringsdatabasenøglen.
Which would translate to something like
Couldn't write to the database registration key
The user running the program has adminstrator rights and the program is run as administrator
How would I go around changing the permission in order to allow the script to be run when the machine starts or is there a better way to achieve the functionality I'm looking for?
key = RegistryKey.OpenBaseKey(
RegistryHive.LocalMachine,
RegistryView.Registry64
).OpenSubKey(subKey);
needs to be:
key = RegistryKey.OpenBaseKey(
RegistryHive.LocalMachine,
RegistryView.Registry64
).OpenSubKey(subKey, true);
to open for modify
Before you try to answer this with, "Do a quick Google search." I'd like to point out that I have already. Here is the situation, I have the following method that attempts to modify a registry key value. The problem I'm getting is that when executed, it throws an UnauthorizedAccessException even though I've opened the key as writeable. I'm running Visual Studio as administrator and even tried to make a small .exe with a manifest file forcing it to run as admin that will execute the code with no luck. The key already exists, it doesn't try to go into the CreateKey method. Here is the block of code.
Path = "S-1-5-21-1644491937-1078145449-682003330-5490\Software\Microsoft\Windows\CurrentVersion\Policies\System"
Key = "DisableTaskMgr"
NewValue = 1
public OperationResult ModifyKey()
{
OperationResult result = new OperationResult();
if (!Path.IsNullOrEmptyTrim())
{
if (!Key.IsNullOrEmptyTrim())
{
try
{
var key = Microsoft.Win32.Registry.Users.OpenSubKey(Path, true);
if (key != null)
{
key.SetValue(Key, NewValue);
key.Close();
}
else
{
result = CreateKey();
}
}
catch (Exception ex)
{
result.SetFail("Error accessing registry", ex);
}
}
else
{
result.SetFail("Registry key was null");
}
}
else
{
result.SetFail("Registry path was null");
}
return result;
}
Do I have to manually walk down the registry tree setting each OpenSubKey call to writeable? I tried this as well, still threw the same error...
in the var for your key
var key = Microsoft.Win32.Registry.Users.OpenSubKey(Path, true);
change to
var key = Microsoft.Win32.Registry.Users.OpenSubKey(Path, RegistryKeyPermissionCheck.ReadWriteSubTree);
Have you tried setting the accessrule and permissions?
string user = Environment.UserDomainName + "\\" + Environment.UserName;
RegistryAccessRule rule = new RegistryAccessRule(user,
RegistryRights.FullControl,
AccessControlType.Allow);
RegistrySecurity security = new RegistrySecurity();
security.AddAccessRule(rule);
var key = Microsoft.Win32.Registry.Users.OpenSubKey(subKeyPath, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl);
key.SetAccessControl(security);
One possible issue that I see with your code is that the Path variable is being set to a string that doesn't escape the \ characters. How about something like:
Path = #"S-1-5-21-1644491937-1078145449-682003330-5490\Software\Microsoft\Windows\CurrentVersion\Policies\System";
As a last ditch effort to figure out what was going on, I created a simple service to test this code that will run as the local system account. It's the highest privileges I could think of to try and run the code with. Running the code with these permissions worked.
Special thanks go out to 0_____0 and Charleh for pointing out the anti-virus as well. I checked the logs and it turns out it was trying to quarantine my changes. I guess even it won't stop the System user from making these changes though.
Special thanks go out to Sorceri as well for helping me research this so much.
In conclusion, if you're having intermittent, extremely odd behavior, check your virus scanner and permissions.
I ran into the same problem recently. So I tried a few things and instead of calling key.SetValue(Key, NewValue) simply calling create function solved my problem. That is;
Microsoft.Win32.RegistryKey key1 = Microsoft.Win32.Registry.Users.CreateSubKey(Path);
key1.SetValue(Key, NewValue);
CreateSubKey call doesn't delete the current entry but provided with the ability to write without exception. I hope that helps.
Only set grants to dword. You must to open Registry and at the last folder path, rigth click over it and set Grants, and select All Aplications and check Total Control. I hope to help you.
just Registry.SetValue(sub_key, key, value);
Example:
Registry.SetValue(
#"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run",
"MyApp",
Application.ExecutablePath);
I have a issue reading a registry value programmatically using C#.
I looked into many sites and help but could not find any helpful.
I am able to access and read registry when I run VS in eleveated mode, but face issue when I run VS with out elevated mode.
Initially I started with the below code
byte[] val = (byte[])Registry.GetValue("HKEY_LOCAL_MACHINE\\Software\\MyServices\\Identity\\ASPNET_SETREG", "ValueName", 0);
This worked fine with elevated mode, but fails in non elevated mode.
Placed the attribute on top of the function
[RegistryPermissionAttribute(SecurityAction.Demand,Unrestricted=true)]
This did not help. Then Tried
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.LinkDemand, Flags = System.Security.Permissions.SecurityPermissionFlag.AllFlags)]
Still did not work.
Now I Tried the below code...
RegistryKey key = Registry.LocalMachine;
RegistrySecurity rs = new RegistrySecurity();
rs = key.GetAccessControl();
string user = "DomainName\\Username";
rs.AddAccessRule(new RegistryAccessRule(user,
RegistryRights.ReadKey,
InheritanceFlags.None,
PropagationFlags.None,
AccessControlType.Allow));
key.SetAccessControl(rs);//Exception: "Attempted to perform an unauthorized operation."}
//RegistryKey key2 = key.OpenSubKey("Software\\MyServices\\Identity\\ASPNET_SETREG");
//RegistryKey key2 = key.OpenSubKey("Software\\MyServices\\Identity\\ASPNET_SETREG", false);
//RegistryKey key2 = key.OpenSubKey("Software\\MyServices\\Identity\\ASPNET_SETREG", RegistryKeyPermissionCheck.ReadSubTree);
RegistryKey key2 = key.OpenSubKey("Software\\MyServices\\Identity\\ASPNET_SETREG", RegistryKeyPermissionCheck.ReadSubTree, RegistryRights.ReadPermissions);
Commenting SetAccessControl and use any of the OpenSubkey option, I get Exception: "Requested registry access is not allowed."
I am badly stuckup and unable to proceed.
private RegistryKey keyR = Registry.CurrentUser.OpenSubKey("Software\\YourKey",true);
private RegistryKey keyW = Registry.CurrentUser.CreateSubKey("Software\\YourKey");
public string version
{
get { return keyR.GetValue("VERSION", "", RegistryValueOptions.DoNotExpandEnvironmentNames).ToString(); }
set { keyW.SetValue("VERSION", value, RegistryValueKind.String); }
}
I am using windows registry in this way. No problem...
The windows registry is basically a structured file system, and has permissions for keys and values.
You do not have the permissions set correctly on ...\MyServices\ or deeper keys - you have no permission to access those from your unprivileged process.
Either:
Those keys should be readable by anybody, so you should change the permissions to make them readable by everybody. Or -
Those keys were intentionally restricted for a good reason, and so they should not be readable by everybody, in which case your program should always run elevated.
what i am trying to do is to have multiple
user names and folder paths in one key.
so i have this structure
HKEY_LOCAL_MACHINE
-- SOFTWARE
-- XYZ
-- userDB
now in userDB i have the info like this
> NAME TYpe Data
>
> Admin Reg_sz C:\Desktop
>
> Admin2 REG_SZ C:\xyz\logs
how can i read the values in userDB...
any suggestions.. thanks
i tried this code:
RegistryKey masterKey = Registry.LocalMachine.CreateSubKey("SOFTWARE\\xyz");
if (masterKey == null)
{
//Console.WriteLine("Null Masterkey!");
}
else
{
table.Rows.Add(false, masterKey.GetValue("userDB"), DateTime.Now);
dataGridView2.DataSource = table;
//Console.WriteLine("MyKey = {0}", masterKey.GetValue("userDB"));
}
masterKey.Close();
but i get the error
Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\xyz' is denied.
While you talk about reading values in your topic, your code actually writes to the registry.
You can't write to most of the HKLM part of the registry by default as a limited user. A limited users may not destroy/manipulate these keys because that's a security risk.
You could have your setup program(running with admin privs) change the permissions for your shared registry key. But that's bad style, and I wouldn't do it.
When using asp.net there might be additional restrictions related to the medium trust model.
You have:
RegistryKey masterKey = Registry.LocalMachine.CreateSubKey("SOFTWARE\\xyz");
RegistryKey.CreateSubKey is documented as:
Creates a new subkey or opens an existing subkey for write access.
Opening for write access most likely requires write privileges.
RegistryKey.OpenSubKey is used to open a key for read access. So it most likely requires no writing privileges.
At which point are you getting access denied? Are you running this code elevated or as administrator?
Chances are you are failing when calling CreateSubKey(), which when writing to HKEY_LOCAL_MACHINE requires elevated permissions.
I think Registry.LocalMachine.CreateSubKey("SOFTWARE\xyz") would try to open the key with write access if that key exists.
Try to open the key with read access instead.
I think that you can use CreateSubKey(String, RegistryKeyPermissionCheck) instead to specify permission access.
For more information, please refer to MSDN: http://msdn.microsoft.com/en-us/library/dd411617.aspx