Запись значения в реестр и удаление из реестра - C#
Формулировка задачи:
Пытался пытался, так и не получилось поладить с api для реестра.
Нужно установить значение и потом удалить.
public bool SetNamedValue(string valName, object value, RegistryValueKind type)
{
UIntPtr hKey = UIntPtr.Zero;
string registryPath;
registryPath = "Test";
try
{
uint retVal = RegOpenKeyEx("HKEY_LOCAL_MACHINE", registryPath, 0, ar, out hKey);
if (retVal == 0)
{
int size = 0;
IntPtr pData = IntPtr.Zero;
switch (type)
{
case RegistryValueKind.String:
size = ((string)value).Length + 1;
pData = Marshal.StringToHGlobalAnsi((string)value);
break;
case RegistryValueKind.DWord:
size = Marshal.SizeOf(typeof(Int32));
pData = Marshal.AllocHGlobal(size);
Marshal.WriteInt32(pData, (int)value);
break;
case RegistryValueKind.QWord:
size = Marshal.SizeOf(typeof(Int64));
pData = Marshal.AllocHGlobal(size);
Marshal.WriteInt64(pData, (long)value);
break;
}
// Set the value
retVal = RegSetValueEx(hKey, valName, 0, type, pData, size);
if (retVal != 0)
{
MessageBox.Show("ОК");
}
}
else
{
MessageBox.Show("Ошибка");
}
}
finally
{
if (hKey != UIntPtr.Zero)
{
RegCloseKey(hKey);
}
}
return true;
}Решение задачи: «Запись значения в реестр и удаление из реестра»
textual
Листинг программы
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
const string Advapi32Dll = "advapi32.dll";
[DllImport(Advapi32Dll, SetLastError = true, CharSet = CharSet.Unicode)]
static extern int RegOpenKeyEx(
UIntPtr hKey,
string lpSubKey,
uint ulOptions,
uint samDesired,
out UIntPtr phkResult
);
[DllImport(Advapi32Dll, SetLastError = true)]
static extern int RegCloseKey(
UIntPtr hKey
);
[DllImport(Advapi32Dll, SetLastError = true, CharSet = CharSet.Unicode)]
static extern int RegSetValueEx(
UIntPtr hKey,
string lpValueName,
uint Reserved,
uint dwType,
byte[] lpData,
int cbData
);
static readonly UIntPtr HKEY_LOCAL_MACHINE = (UIntPtr)(0x80000002);
const uint KEY_SET_VALUE = 0x2;
const uint REG_SZ = 0x1;
const int ERROR_SUCCESS = 0;
static void Main(string[] args)
{
UIntPtr hKey;
int error = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SYSTEM", 0, KEY_SET_VALUE, out hKey);
if (ERROR_SUCCESS != error)
{
Console.WriteLine("RegOpenKeyEx error: " + error);
return;
}
string value = "test";
byte[] buffer = new byte[Encoding.Unicode.GetByteCount(value) + sizeof(char)];
Encoding.Unicode.GetBytes(value, 0, value.Length, buffer, 0);
error = RegSetValueEx(hKey, "test", 0, REG_SZ, buffer, buffer.Length);
if (ERROR_SUCCESS != error)
{
Console.WriteLine("RegSetValueEx error: " + error);
}
RegCloseKey(hKey);
}
}
}