Click here to Skip to main content
15,889,876 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to create a registry key so that my application runs when windows starts, and I tried the following code:

C#
string strRegKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
string path = \\path of my application
RegistryKey regkey = Registry.LocalMachine.OpenSubKey(strRegKey, true);
regkey = Registry.LocalMachine.CreateSubKey(strRegKey);
regkey.SetValue("sys", path, RegistryValueKind.String);


The compiler gave an error at regkey.SetValue:

"Attempted to perform an unauthorized operation"

Please tell me how I can solve this problem?
Posted
Updated 10-Feb-10 6:33am
v3

thank you Wjousts
i modifed my code to be like this :
string strRegKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
string path = \\path of my application 
RegistryKey regkey = Registry.LocalMachine.CreateSubKey(strRegKey);
regkey.SetValue("sys", path, RegistryValueKind.String);

and then i got exception:
UnauthorizedAccessException
that told my that registry key is read only
so how can i write to this location because many program run when windows startup by writing the path of exe file to this location in registry .
and i tried it manual and it worked but i want to do it in my application .
so can you help me
 
Share this answer
 
v2
You are writing to HKLM, if memory serves, I think you need administrator access to do that. Are you running your app as administrator? If not, you could try writing to HKCU instead. HKCU obviously will only effect the current user rather than everybody who uses the computer which may or may not be what you are trying to do.
 
Share this answer
 
thank you again Wjousts
i tried to run my application "as adminstrator" and its worked
and i will tring to write in "current user" without running my application as adminstrator .
but my problem only happened in vista system
so thank you your answers were very helpful
 
Share this answer
 
First, why are your using OpenSubKey and then CreateSubKey to open the same key? CreateSubKey alone should be enough.
Second, I'm assuming you actually mean a run-time error rather than a compiler error? In that case, what is the type of the exception? Then check the MSDN for why it's happening (http://msdn.microsoft.com/en-us/library/k23f0345.aspx[^]).
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900