I am trying to change certain value in the registry programmatically (C#) but I am constantly running into Unauthorized-Access-Exceptions.
The registry-keys that I am trying to modify have been created by a driver-installer for an USB-audio-Device. This device (a LogiLink USB Sound Box 7.1) sometimes “forgets” its settings and I am looking for a quick way to re-set the settings automatically.
Reading the values with the usual Microsoft.Win32.Registry-methods is no problem, but trying to overwrite certain values seems to be difficult.
However, doing the changes manually (using regedit) is no problem. I do have admin rights as a User and I am starting all my C# programs that ought to modify the values “as Administrator”, but to no avail.
Here are a few things I have tried:
-Giving my application Admin-rights in the app.manifest.
-Tring to open the Key with the Microsoft.Win32-methods with the writable = true. Here I get an System.UnauthorizedAccessException.
RegistryKey key =
RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine,
RegistryView.Registry64);
key = key.OpenSubKey(regPath,true);
-Exporting the key into a *.reg-file using reg. (always works)
String strCmdText = "/C REG EXPORT <KeyPath> <ExportPath> /reg:64";
System.Diagnostics.Process.Start("CMD.exe", strCmdText);
Then I can modify the resulting file and try to import it using various methods.
String strCmdText = "/C REG IMPORT <PathToReg> /reg:64";
System.Diagnostics.Process.Start("CMD.exe", strCmdText);
Or
String strCmdText = <PathToReg>;
System.Diagnostics.Process.Start("REGEDIT.exe", strCmdText);
I tried those methods in other places in the registry and they work flawlessly, however they fail if I want to apply them to the keys of the USB-audio-Device. The Processes always end with return-code 0.
Manually importing the exported and modified *.reg-file always works and the Device-Settings are changed as expected. Even using the CMD-Console manually yields the desired result. However, if I try to do the exact same thing in C#, no change is happening (even with admin-rights).
I would be very glad if someone had an idea about this. Thank you.
Related
I'm trying to use this registry hack I found online:
;Disables F1 key - Help and Support - in Windows 10
;Ramesh Srinivasan, Winhelponline.com
[HKEY_CURRENT_USER\SOFTWARE\Classes\Typelib\{8cec5860-07a1-11d9-b15e-000d56bfe6ee}\1.0\0\win32]
#=""
[HKEY_CURRENT_USER\SOFTWARE\Classes\Typelib\{8cec5860-07a1-11d9-b15e-000d56bfe6ee}\1.0\0\win64]
#=""
When I run it as a .reg command via Windows Explorer and watch the registry with regedit, it works as intended. Removing it is another registry file that simply removes the \0 subkey (and win32 and 64 with it). I'm trying to emulate this function with C# in a Winform using .net CORE:
private void CheckF1()
{
// Registry data from ;Ramesh Srinivasan, Winhelponline.com
RegistryKey F1key = Registry.CurrentUser.OpenSubKey(#"SOFTWARE\Classes\TypeLib\{8cec5860-07a1-11d9-b15e-000d56bfe6ee}\1.0\0");
// EGADS! It's active!
if (F1key == null)
{
fckF1RestoreBtn.Enabled = false;
fckF1KillBtn.Enabled = true;
fckF1Status.Text = "That creepy bugger is waiting and watching.";
}
else
{
fckF1RestoreBtn.Enabled = true;
fckF1KillBtn.Enabled = false;
fckF1Status.Text = "The F1-Help function had been put in it's place.";
}
}
private void fckF1KillBtn_Click(object sender, EventArgs e)
{
Registry.CurrentUser.CreateSubKey(#"SOFTWARE\Classes\Typelib\{8cec5860-07a1-11d9-b15e-000d56bfe6ee}\1.0\0\win32");
Registry.CurrentUser.CreateSubKey(#"SOFTWARE\Classes\Typelib\{8cec5860-07a1-11d9-b15e-000d56bfe6ee}\1.0\0\win64");
CheckF1();
}
private void fckF1RestoreBtn_Click(object sender, EventArgs e)
{
Registry.CurrentUser.DeleteSubKeyTree(#"SOFTWARE\Classes\Typelib\{8cec5860-07a1-11d9-b15e-000d56bfe6ee}\1.0\0");
CheckF1();
}
Weirdly the code "sees" a setting and responds like it should. Even to the point that whichever toggle position it was in on close it remembers when I load the file again. It's almost like it's playing along to screw with me. Regardless, when I watch the registry, none of my code has any actual effect though by all appearances it seems to work otherwise (it doesn't actually of course because the registry change isn't happening).
NOTE: I have already updated my manifest file for the project to include elevated permissions:
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
Here's the breakpoint on the test statement to see if the subkeys are there that shows they are:
Meanwhile the registry location for the exact path shown in the debug doesn't have the 1.0\0 path at all:
I don't know how the code is reading phantom values. Someone closed my previous question pointing to another answer that didn't have any effect (Registry key deleted but still getting value from registry c#):
"Prefer 32 bit" was never checked for my project in the first place
Modifying my code as recommended had no effect
var key = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64)
.OpenSubKey(#"SOFTWARE\WOW6432Node\Classes\TypeLib\{8cec5860-07a1-11d9-b15e-000d56bfe6ee}\1.0\0");
Adding "Wow64Node" to the path makes no difference in execution.
EXPECTED BEHAVIOR
Checking to see if the HKEY_CURRENT_USER\SOFTWARE\Classes\Typelib{8cec5860-07a1-11d9-b15e-000d56bfe6ee}\1.0\0 path is present should return null if the \0 path is not present
Adding and removing the subkeys should show in the registry
So apparently HKEY_CURRENT_USERS is an alias. When the above code runs, it updates in HKEY_USERS under the specific logged in user. There's a question that talks about this behavior here: write registry to hkey_current_user instead of hkey_users
That said, the code appears to work, it's just that the registry doesn't update HKCU like when you run .reg commands. To verify it was working, I'd run the toggle that kills the keys then click them in Regedit and it would say they didn't exist. When I toggled back, I could click on them. So basically, it works (not sure if it required the "using" blocks as others suggested, but I see no reason to take them out).
Now my problem is that it points to the admin user and NOT the regular user because I'm running it and regedit as admin. It took forever to determine this based on running regedit as user in one case and admin in another. Bottom line, this won't work and I'll probably end up running .reg files in the command line instead.
I want to delete a folder named EXAMPLE and all values in it in registry that is found under "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\EXAMPLE"
i have tried this ( with true at the end aswell )
Microsoft.Win32.Registry.LocalMachine.DeleteSubKeyTree(#"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\EXAMPLE");
and tried this
string keyName = #"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(keyName, true))
{
key.DeleteSubKeyTree("EXAMPLE", true);
}
They either throw me a null exception or argument exception.
How can i just delete an entire folder with all its keys ?
So that i can have the similar effect from batch :
REG DELETE "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\EXAMPLE" /f
The path is incorrect, Registry.LocalMachine doesn't have such a sub key #"HKEY_LOCAL_MACHINE\...". You need to start from "SOFTWARE\..".
string keyName = #"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
And from your feedback, your program is affected by the Registry Redirector, in which HKEY_LOCAL_MACHINE\Software is redirected to HKEY_LOCAL_MACHINE\Software\Wow6432Node for a 32-bit program, recompile your program from AnyCPU (Prefer 32-bit) to x64 gets rid of the redirection.
The mechanism of Registry Redirector varies on different Windows versions, so I leave this to you for further reading to understand why 64/32 matters in this case.
I have searched everywhere to find out how to make a custom minecraft launcher. I managed to create this code, which should work, but sadly it does not. I login but it never starts, however for a second I get the loading ring next to my mouse. This is my code:
ProcessStartInfo start = new ProcessStartInfo();
// Enter in the command line arguments, everything you would enter after the executable name itself
start.Arguments = #"-Xmx1G -Djava.library.path=%APPDATA%\.minecraft\versions\1.6.2\1.6.2-natives -cp %APPDATA%\.minecraft\libraries\net\sf\jopt-simple\jopt-simple\4.5\jopt-simple-4.5.jar;%APPDATA%\.minecraft\libraries\com\paulscode\codecjorbis\20101023\codecjorbis-20101023.jar;%APPDATA%\.minecraft\libraries\com\paulscode\codecwav\20101023\codecwav-20101023.jar;%APPDATA%\.minecraft\libraries\com\paulscode\libraryjavasound\20101123\libraryjavasound-20101123.jar;%APPDATA%\.minecraft\libraries\com\paulscode\librarylwjglopenal\20100824\librarylwjglopenal-20100824.jar;%APPDATA%\.minecraft\libraries\com\paulscode\soundsystem\20120107\soundsystem-20120107.jar;%APPDATA%\.minecraft\libraries\argo\argo\2.25_fixed\argo-2.25_fixed.jar;%APPDATA%\.minecraft\libraries\org\bouncycastle\bcprov-jdk15on\1.47\bcprov-jdk15on-1.47.jar;%APPDATA%\.minecraft\libraries\com\google\guava\guava\14.0\guava-14.0.jar;%APPDATA%\.minecraft\libraries\org\apache\commons\commons-lang3\3.1\commons-lang3-3.1.jar;%APPDATA%\.minecraft\libraries\commons-io\commons-io\2.4\commons-io-2.4.jar;%APPDATA%\.minecraft\libraries\net\java\jinput\jinput\2.0.5\jinput-2.0.5.jar;%APPDATA%\.minecraft\libraries\net\java\jutils\jutils\1.0.0\jutils-1.0.0.jar;%APPDATA%\.minecraft\libraries\com\google\code\gson\gson\2.2.2\gson-2.2.2.jar;%APPDATA%\.minecraft\libraries\org\lwjgl\lwjgl\lwjgl\2.9.0\lwjgl-2.9.0.jar;%APPDATA%\.minecraft\libraries\org\lwjgl\lwjgl\lwjgl_util\2.9.0\lwjgl_util-2.9.0.jar;%APPDATA%\.minecraft\versions\1.6.2\1.6.2.jar net.minecraft.client.main.Main --username playername --session token:"+ words[3] + #":" + words[4]+ #" --version 1.6.2 --gameDir %APPDATA%\.minecraft --assetsDir %APPDATA%\.minecraft\assets";
start.FileName = #"c:\Program Files (x86)\java\jre7\bin\javaw.exe";
// Do you want to show a console window?
start.CreateNoWindow = true;
System.Diagnostics.Process.Start(start);
This just does the loading ring by my mouse for a second, then nothing opens. No logs, crashes, errors, nothing wrong. This is Visual c# compiled on Visual Studio 2012.
The arguments you are giving have an environment variable in them - %APPDATA%.
The command line will expand this by default, but the .net library won't.
See How do I ensure c# Process.Start will expand environment variables?
As Pete Kirkham mentioned you need to set up environment variable.
You can set it before starting the Process like:
var appDataPath = "your path";
start.EnvironmentVariables.Add("APPDATA", appDataPath);
I am fairly new to coding, but have built a few small things. One thing I figured out on my last project was how to run 2 simple commands normally run from a console, but from within a form application instead. Simply, the form had 2 buttons and clicking one caused ipconfig to run and the other ipconfig /all. It then posted the ip information coming from the command into another form I created as a message box. That is important because I am trying to do something similar and nothing is working now.
I have a form that has a spot for user name and a spot for password. On submit, I want it to essentially run the following:
NET USE F: \\ALPHA\CLIENTAPPS /user:domain\%username% %password% /persistent:no
NET USE O: \\ALPHA\USERS /user:domain\%username% %password% /persistent:no
NET USE S: \\ALPHA\COMPANY /user:domain\%username% %password% /persistent:no
Where %username% and %password% are captured from the form and domain will be our actual domain.
Using similar methods to the aforementioned ipconfig program that is working, this is what I came up with. However, when I click the Submit button, nothing happens, no errors, nor does it actually create the network share:
private void btnSubmit_Click(object sender, EventArgs e)
{
string un = txtUsername.Text;
string pw = txtPassword.Text;
System.Diagnostics.ProcessStartInfo PR = new System.Diagnostics.ProcessStartInfo("cmd", #" /c net use W: \\\\ALPHA\\CLIENTAPPS /user:acsdish\\" + un + " " + pw + "/persistent:no");
PR.RedirectStandardOutput = true;
PR.UseShellExecute = false;
PR.CreateNoWindow = true;
System.Diagnostics.Process StartPR = new System.Diagnostics.Process();
StartPR.StartInfo = PR;
StartPR.Start();
}
What am I missing here, or is there a better way? Thanks.
Mike
System.Diagnostics.ProcessStartInfo PR = new System.Diagnostics.ProcessStartInfo("cmd", #" /c net use W: \\\\ALPHA\\CLIENTAPPS /user:acsdish\\" + un + " " + pw + "/persistent:no");
Try to remove "#" or remove escaping of "\" char
Info here (Verbatim string literals)
nothing happens, no errors, nor does it actually create the network share
You've done a lot to ensure that. "No errors" is easy to explain, you don't check for errors nor do you give a way for the user to see them because you made sure that the console window isn't visible. If the command failed that it won't be visible. Checking Process.ExitCode is a minimal requirement.
Next flaw is that you create the mapping to the share for a particular user. Which is fine, drive mappings are a per-user setting. But you are not actually logged-in as that user so you can't see those mappings. You'll have to hit Ctrl+Alt+Del and switch the user account. But that's a lost cause because you passed /persistent:no. That means "persistent while the user is logged in".
Ultimate flaw is that you leave it up to an another process to take care of it. That always loses critical information, especially errors. You should pinvoke the Windows api function that does this so you know when it doesn't work and don't burn a gazillion cycles to run another process. Pinvoke WNetAddConnection2().
This one seems trivial but the answer has eluded me for a few days now.
I have a Windows batch file, that calls a C# program to do an extra verification that cannot be done in a batch file. After the verification is complete I need to return a status and a string back to the calling shell.
Now the return value is trivial and my C# console app simply sets a return value (exit code if you will). And I thought the string will also be a piece of cake. I attempted to define a new shell variable using the:
Environment.SetEnvironmentVariable("ERR", "Some text");
This call should (and does) define a shell variable within the current process - that is the very C# process that created the variable. The value is lost as soon as the C# app terminates and the shell that created the C# app knows nothing about the variable. So... A call with no particular use... At all... Unless perhaps if I created a child process from the C3 app, perhaps it would inherit my variables.
The EnvironmentVariableTarget.Machine and EnvironmentVariableTarget.User targets for the SetEnvironmentVariable call don't solve the problem either, as only a newly created process will get these new values from the registry.
So the only working solution I can think of is:
write to stdout
write to a file
encode extra meaning into the return value
The first two are a bit ugly and the last one has its limitations and problems.
Any other ideas (how to set a shell variable in the parent process)? Maybe such shell variable modifications are a security concern (think PATH)...
Thank-you for your time.
I had the same problem as Ryan and the only thing that came to my mind as a work-around was to write a batch in error out to set the variable and to call it from the batch.
ConsoleApplication1.exe:
'put some sensible code here
'put result in variable myResult
Dim myResult As String = Guid.NewGuid().ToString("D").ToUpperInvariant()
Console.WriteLine("Normal output from the consonle app")
Console.Error.WriteLine("#ECHO OFF")
Console.Error.WriteLine("SET zzzResult={0}", myResult)
Test.cmd (the calling batch):
#ECHO OFF
:Jump to folder of batch file
PUSHD %~d0%~p0
:Define a temp file
SET zzzTempFile=%TEMP%\TMP%Random%.CMD
:Call .NET console app
ConsoleApplication1.exe 2>%zzzTempFile%
:Call the generated batch file
CALL %zzzTempFile%
:Clean up temp file
DEL %zzzTempFile%
:Clean up variable
SET zzzTempFile=
:Do something with the result
ECHO Yeah, we finally got it!
ECHO:
ECHO The value is "%zzzResult%".
ECHO:
:Clean up result variable
SET zzzResult=
:Go back to original folder
POPD
That should do the trick. And yes, I do know this is an old post and Ryan is solving other issues by now, but there might be still somebody else out there having the same problem...
What you are asking is to be able to arbitrarily write to the memory space of a running process. For good reason, this is not possible without SeDebugPrivilege.
Any of the three solutions you list will work. Stdout is the standard way to communicate with a batch script.
By the way, you're writing a Windows batch file. I'm pretty sure the ship has already sailed on "a bit ugly".
If you want to put a value of some output into a variable in the batch you can use the following construct:
FOR /F "usebackq tokens=4 delims=\[\] " %i IN (`ver`) DO set VERSION=%i
ECHO %VERSION%
Output on my OS:
6.1.7601
'usebackq' means we are using back quotes which gives the ability to use a fileset in the command quoted with double quotes. You may not need this. 'tokens' means the index in the resulting string array to select (it can be a range M-N). If you need to skip lines use 'skip=X'). 'delims' are the string separators to use (like string-Split() in .Net).
You will put your console app instead of 'ver' and adapt the delimiters and tokens to match your specific output. If you have more variables to fill you will need to make the if a bit more complex but that should make a good start.
My BAT is a bit rusty, but I think it's possible to retrieve the 'exit' code from processes you've run externally, perhaps via %ERRORLEVEL%. If that's the case, make sure to exit your program via
Environment.Exit(123); // where 123 = error code
You can't add any messages, so you'll have to do that in the .bat file.
If this isn't the case, stdout is probably the best way.
After stumbling on this myself as well recently, I came up with this approach. What I did is run the bat file using the Process class, i.e.
// Spawn your process as you normally would... but also have it dump the environment varaibles
Process process = new Process();
process.StartInfo.FileName = mybatfile.bat;
process.StartInfo.Arguments = #"&&set>>envirodump.txt";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = false;
process.Start();
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
// Read the environment variable lines into a string array
string[] envirolines = File.ReadAllLines("envirodump.txt");
File.Delete("envirodump.txt");
// Now simply set the environment variables in the parent process
foreach(string line in a)
{
string var = line.Split('=')[0];
string val = line.Split('=')[1];
Environment.SetEnvironmentVariable(var, val);
}
This seems to have worked for me. It's not the cleanest approach, but will work in a bind. :)