How to use registry to refill a text box - c#

How can i refill a textbox with it's previous text after the program was stopped using registry.
I read multiple articles like:
Stack OverFlow1
Stack OverFlow2
Code Project1
Code Project2
So far i have nothing because nothing is working out, all i get are errors D:
public string Read(string KeyName)
{
RegistryKey rk = baseRegistryKey ;
RegistryKey sk1 = rk.OpenSubKey(subKey);
if ( sk1 == null )
return null;
else
{
try
{
return (string)sk1.GetValue(KeyName.ToUpper());
}
catch (Exception ex)
{
}
}
}
says that baseRegistryKey and subKey don't exist. And it says that RegistryKey doesn't exist. How do i fix?

I've had the same problem a couple of days ago, don't use those sights, they are all bad.
there are several things wrong with your code:
baseRegistryKey and subKey need to be set to some sort of a parameter.
if RegisterKey isn't working than you probably didn't do using Microsoft.Win32
The code i used to solve this was:
public WindowsConsoleForm1();
try
{
InitializeComponent();
textBox1.Text = Application.UserAppDataRegistry.GetValue("example").ToString();
}
catch { }
and then where ever you have ex: textbox1.text = Path.GetDirectoryName(saveFileDialoge1.FileName);, under it you post Application.UserAppDataRegistry.SetValue("example", textbox1.text);

Related

How to set a RegistryKey Value in Visual Studio?

I have a Project and i am trying to run the installer on a new pc to test my WPF application, but the registry key is not automatically created. I have tried adding it manually but i don't know why it is not working, i am sure i am not adding the key the right way. Also i am confused since it is a new PC how do i add something that will automatically create a path?
The one that i am creating is something like this in the Image:
[VS Image][1]
HKLM -- do you have Admin right? really privileged rights?
How to test that you have enough right to write to HKLM (just call OpenSubKey):
public bool CanSetRegKeyValue(string path, string valueName, RegistryKey registry = null)
{
bool result = true;
try
{
RegistryKey registryKey = null;
if (registry == null)
{
registryKey = Registry.LocalMachine;
}
using (RegistryKey key = registryKey.OpenSubKey(path, true))
{
result = key != null;
}
}
catch (NullReferenceException)
{
result = false;
}
catch (SecurityException)
{
result = false;
}
return result;
}
and usage sample, which checking write ability to Key DefaultLevel under node HKLM\SOFTWARE\Policies\Microsoft\Windows\safer\codeidentifiers:
bool result = CanSetRegKeyValue("SOFTWARE\\Policies\\Microsoft\\Windows\\safer\\codeidentifiers\\", "DefaultLevel");

How to launch the user's default browser with search criteria?

I found this link:
C# Launch default browser with a default search query
But with FireFox as my default browser, it tries to find a file named as whatever is in the quotes in the selected Answer there.
Code;
//ToolStripMenu Click event to launch default browser and search internet for the value in a particular cell
private void tsmSearch_Click(object sender, EventArgs e)
{
int key = mp.GetRowAt(gdcErrorLogDefaultView, rowX, rowY);
if (key < 0)
return;
string ex = gdcErrorLogDefaultView.GetRowCellValue(key, "Exception").ToString();
string name = GetDefaultBrowser();
Process.Start(name, "\"?" + ex + "\"");
}
//Gets default browser from registry
private string GetDefaultBrowser()
{
string name;
RegistryKey regKey = null;
try
{
//set the registry key we want to open
regKey = Registry.ClassesRoot.OpenSubKey("HTTP\\shell\\open\\command", false);
//get rid of the enclosing quotes
name = regKey.GetValue(null).ToString().ToLower().Replace("" + (char)34, "");
//check to see if the value ends with .exe (this way we can remove any command line arguments)
if (!name.EndsWith("exe"))
//get rid of all command line arguments (anything after the .exe must go)
name = name.Substring(0, name.LastIndexOf(".exe") + 4);
}
catch (Exception ex)
{
name = string.Format("ERROR: An exception of type: {0} occurred in method: {1} in the following module: {2}", ex.GetType(), ex.TargetSite, this.GetType());
}
finally
{
//check and see if the key is still open, if so
//then close it
if (regKey != null)
regKey.Close();
}
return name;
}
I found the GetDefaultBrowser() code somewhere on StackOverflow yesterday but I can't find the link now. The weird thing is though, I have Chrome set as my default browser but that registry key still says FireFox.
Is there a more simple way to launch the default browser and use their default search provider to look up a term?
Try this:
string searchQuery = "this is a search";
Process.Start("https://www.google.com/search?q=" + Uri.EscapeDataString(searchQuery));
Edit: Now using correct Google link

How to read value of a registry key c#

At start up of my application I am trying to see if the user has a specific version of a software installed, specifically the MySQL connector, all using c#. In the registry, the MySQL contains a version entry. So what I am trying to accomplish is this.
My app starts up. Somewhere in the start up code I need to do the following things in order. Check to see if the user has the MySQL connector installed, which is located at...
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MySQL AB\MySQL Connector/Net
If the user has the connector installed, I wanted to check what version they have, which is stored as Name = "Version" and Data = x.x.x (Picture below)
Now if the user has a specific version installed, then I will execute other code, which is where I can take from.
What would be the best way of going about this?
EDIT: Below is the code I currently have and I am getting an error on line 19 (It is commented). My error says "error CS1001: Identifier Expected" I wasnt able to figure out what that means. Any help?
using System;
using Microsoft.Win32;
using System.Data;
public class regTest
{
public static void Main()
{
try
{
RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net");
if (key != null)
{
Object o = key.GetValue("Version");
if (o != null)
{
Version version = new Version(o as String); //"as" because it's REG_SZ...otherwise ToString() might be safe(r)
Version broken = new Version("6.7.4");
if (version.Equals.(broken)) //This is where the error is occuring
{
DataSet dataSet = ConfigurationManager.GetSection("system.data") as ystem.Data.DataSet;
DataView vi = dataSet.Tables[0].DefaultView;
vi.Sort = "Name";
if (vi.Find("MySql") == -1)
{
dataSet.Tables[0].Rows.Add("MySql"
, "MySql.Data.MySqlClient"
, "MySql.Data.MySqlClient"
,
typeof(MySql.Data.MySqlClient.MySqlClientFactory).AssemblyQualifiedName);
}
}
}
}
}
catch (Exception ex) //just for demonstration...it's always best to handle specific exceptions
{
//react appropriately
}
}
}
You need to first add using Microsoft.Win32; to your code page.
Then you can begin to use the Registry classes:
try
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))
{
if (key != null)
{
Object o = key.GetValue("Version");
if (o != null)
{
Version version = new Version(o as String); //"as" because it's REG_SZ...otherwise ToString() might be safe(r)
//do what you like with version
}
}
}
}
catch (Exception ex) //just for demonstration...it's always best to handle specific exceptions
{
//react appropriately
}
BEWARE: unless you have administrator access, you are unlikely to be able to do much in LOCAL_MACHINE. Sometimes even reading values can be a suspect operation without admin rights.
#DonBoitnott have a good code, but require admin rights. I use this (only need Read Rights)
try
{
var subKey = "Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net";
using (var key = Registry.LocalMachine.OpenSubKey(subKey, false)) // False is important!
{
var s = key?.GetValue("Version") as string;
if (!string.IsNullOrWhiteSpace(s))
{
var version = new Version(s);
}
}
}
catch (Exception ex) //just for demonstration...it's always best to handle specific exceptions
{
//react appropriately
}
Change:
using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))
To:
using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\Wow6432Node\MySQL AB\MySQL Connector\Net"))

How To Edit The Registy Values in Windows (the regedit) via Code in C#? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Looking for C# registry class
Way to write on registry location
I'm trying to make a program in C# that boosts the speed of windows by doing a couple of things (clearing temp folder , prefetch folder ... etc)
but to make the program strong, I need to edit the registry values ..
how can i do that ?
You may need to read this article
public string Read(string KeyName)
{
// Opening the registry key
RegistryKey rk = baseRegistryKey ;
// Open a subKey as read-only
RegistryKey sk1 = rk.OpenSubKey(subKey);
// If the RegistrySubKey doesn't exist -> (null)
if ( sk1 == null )
{
return null;
}
else
{
try
{
// If the RegistryKey exists I get its value
// or null is returned.
return (string)sk1.GetValue(KeyName.ToUpper());
}
catch (Exception e)
{
// AAAAAAAAAAARGH, an error!
ShowErrorMessage(e, "Reading registry " + KeyName.ToUpper());
return null;
}
}
}
With the Microsoft.Win32.RegistryKey class.

Read a Registry Key

I have a web application which is importing DLLs from the bin folder.
const string dllpath = "Utility.dll";
[DllImport(dllpath)]
Now what I want to do is first import the DLLs from a folder not in the current project but at some different location.
The path of that folder is stored in a registry key.
How should I do this?
Edit:
Why can't I work this out???
public partial class Reports1 : System.Web.UI.Page
{
RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(#"Software\xyz");
string pathName = (string)registryKey.GetValue("BinDir");
const string dllpath = pathName;
[DllImport(dllpath)]
public static extern bool GetErrorString(uint lookupCode, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder buf, uint bufSize);
protected void Page_Load(object sender, EventArgs e)
{
string pathName = (string)registryKey.GetValue("BinDir"); is not working here, but is working in the pageload event...
But if I do this DLL import won't work...
How can I fix this?
Reading the registry is pretty straightforward. The Microsoft.Win32 namespace has a Registry static class. To read a key from the HKLM node, the code is:
RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("Software\\NodeName")
If the node is HKCU, you can replace LocalMachine with CurrentUser.
Once you have the RegistryKey object, use GetValue to get the value from the registry. Continuing Using the example above, getting the pathName registry value would be:
string pathName = (string) registryKey.GetValue("pathName");
And don't forget to close the RegistryKey object when you are done with it (or put the statement to get the value into a Using block).
Updates
I see a couple of things. First, I would change pathName to be a static property defined as:
Private static string PathName
{
get
{
using (RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(#"Software\Copium"))
{
return (string)registryKey.GetValue("BinDir");
}
}
}
The two issues were:
The RegistryKey reference will keep the registry open. Using that as a static variable in the class will cause issues on the computer.
Registry path's use forward slashes, not back slashes.
None of these answers worked for me. This is what I used:
static void Main()
{
const string dotNetFourPath = "Software\\Microsoft";//note backslash
using (RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(dotNetFourPath))
{
Console.WriteLine(registryKey.SubKeyCount);//registry is not null
foreach (var VARIABLE in registryKey.GetSubKeyNames())
{
Console.WriteLine(VARIABLE);//here I can see I have many keys
//no need to switch to x64 as suggested on other posts
}
}
}
All these answers may lead to problems running on 64bit OS - which is usual nowadays.
In my situation, i compile to 'Any CPU' target and the software is working fine when i install on 64bit OS.
But my unit tests are running into problems - obviously they are executed in 32bit mode.
In this case not the HKEY_LOCAL_MACHINE\SOFTWARE\MyCompany\MySoftware is searched but HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\MyCompany\MySoftware but there are no entries!
In this situation we have to specify the start point of our search using
RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)
In total we can use.
string configurationDirectory = string.Empty;
using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
{
using (RegistryKey registryKey = hklm.OpenSubKey(#"SOFTWARE\MyCompany\MySoftware"))
{
if (registryKey != null)
{
configurationDirectory = (string)registryKey.GetValue("ConfigurationDirectory");
}
}
}
try
{
RegistryKey regKey = Registry.LocalMachine;
regKey = regKey.OpenSubKey(#"Software\Application\");
if (regKey != null)
{
return regKey.GetValue("KEY NAME").ToString();
}
else
{
return null;
}
}
catch (Exception ex)
{
return null;
}
You can use this:
/// <summary>
/// To read a registry key.
/// input: KeyName (string)
/// output: value (string)
/// </summary>
public string Read(string KeyName)
{
// Opening the registry key
RegistryKey rk = baseRegistryKey ;
// Open a subKey as read-only
RegistryKey sk1 = rk.OpenSubKey(subKey);
// If the RegistrySubKey doesn't exist -> (null)
if ( sk1 == null )
{
return null;
}
else
{
try
{
// If the RegistryKey exists I get its value
// or null is returned.
return (string)sk1.GetValue(KeyName.ToUpper());
}
catch (Exception e)
{
// AAAAAAAAAAARGH, an error!
ShowErrorMessage(e, "Reading registry " + KeyName.ToUpper());
return null;
}
}
}
For more information visit this web site .

Categories

Resources