2011-08-29 30 views
36

Estoy tratando de escribir en el registro usando mi aplicación C#.Escribiendo al registro en una aplicación C#

estoy usando la respuesta dada aquí: Writing values to the registry with C#

Sin embargo, por alguna razón no se añade la clave para el registro.

estoy usando el siguiente código:

string Timestamp = DateTime.Now.ToString("dd-MM-yyyy"); 

string key = "HKEY_LOCAL_MACHINE\\SOFTWARE\\"+Application.ProductName+"\\"+Application.ProductVersion; 
string valueName = "Trial Period"; 

Microsoft.Win32.Registry.SetValue(key, valueName, Timestamp, Microsoft.Win32.RegistryValueKind.String); 

Los Application.name y Application.version 'carpetas' No existe todavía.

¿Tengo que crearlos primero?

Además, lo estoy probando en una versión Win de 64b, así que creo que si deseo comprobar el registro de la clave añadida, debo verificar específicamente el registro de 32 bits en: C: \ Windows \ SysWOW64 \ regedit.exe ¿no?

+2

UAC va a arruinar sus planes, no puede escribir a HKLM sin elevación. A menos que escriba un instalador que cambie la accesibilidad de la clave.El código de ejecución de licencia es el tipo de código que compra. Se necesita un centavo para hacer un centavo. –

+0

debe usar la aplicación de cuadro. debe ayudarte –

Respuesta

57

primer lugar si desea editar llave bajo LocalMachine debe ejecutar su aplicación en virtud de derechos de administrador (mejor uso CurrentUser que es más seguro o crear la llave en el instalador). También debe abrir la tecla en el modo de edición (método OpenSubKey) para agregar nuevas subclaves. Revisé el código y funciona. Aquí está el código.

RegistryKey key = Registry.LocalMachine.OpenSubKey("Software",true); 

key.CreateSubKey("AppName"); 
key = key.OpenSubKey("AppName", true); 


key.CreateSubKey("AppVersion"); 
key = key.OpenSubKey("AppVersion", true); 

key.SetValue("yourkey", "yourvalue"); 
+2

Es más seguro escribir datos en la carpeta de usuario - Microsoft.Win32.Registry.CurrentUser - en lugar de en la computadora local - Microsoft.Win32.Registry.LocalMachine. http://msdn.microsoft.com/en-us/library/h5e7chcf.aspx –

+0

Intenté hacer algo básicamente igual, pero usando la metodología 'using'. Eso causó algunos problemas extraños cuando la clave era nula, así que intenté esto en su lugar sin que se desencadenaran problemas debido a las excepciones de clave nula. ¡Día feliz! ^^ –

1

Primero intente abrir HKLM\Software. Luego crea la clave para tu programa y luego crea la clave para la versión. Sin embargo, su clave podría colocarse en HKLM \ software \ WOW6432Node. Mira esto.

6

También compruebe si sus llamadas de registro se están virtualizando. Vea here para más información.

Puede suceder si su aplicación no es UAC aware y se produce por razones de compatibilidad.

Real path 
HKEY_LOCAL_MACHINE\Software\FooKey 

Virtual path 
HKEY_USERS\<User SID>_Classes\VirtualStore\Machine\Software\FooKey 
3

Puede usar el siguiente código para crear y abrir las claves de registro requeridas.

RegistryKey SoftwareKey = Registry.LocalMachine.OpenSubKey("Software",true); 

RegistryKey AppNameKey = SoftwareKey.CreateSubKey("AppName"); 
RegistryKey AppVersionKey = AppNameKey.CreateSubKey("AppVersion"); 

AppVersionKey.SetValue("yourkey", "yourvalue"); 

básicamente Puede utilizar CreateSubKey para todos los parámetros de la aplicación, ya que se abrirá la llave para acceso de escritura, si ya existe, y crear de otra manera. No es necesario crear primero, y luego abrir. OpenSubKey es muy útil cuando se está absolutamente seguro de que la clave ya existe, como en este caso, la "HKEY_LOCAL_MACHINE \ SOFTWARE \"

-3

Gracias a todos por sus aportaciones y ayudas

A continuación se muestra la solución de trabajo final se me ocurrió con. Se integra con otras colecciones similares. Inicialmente usé una lista pero necesitaba una cadena como clave para las otras colecciones

// ************************** Ordered Dictionary - works **************** 
// http://stackoverflow.com/questions/2722767/c-sharp-order-preserving-data-structures 
// http://www.go4expert.com/articles/understanding-c-sharp-dictionaries-t30034/ 

public OrderedDictionary m_oCol; 
public OrderedDictionary m_oColReverse; 

public clsFeatureCollection() 
    : base() 
{ 
    m_oCol = new OrderedDictionary(); 
    m_oColReverse = new OrderedDictionary(); 
} 

public IEnumerator GetEnumerator() 
{ 
    return m_oCol.GetEnumerator(); 
} 

public void Add(IFeature pFeature, string strBefore = "", string strAfter = "", bool bReverse = false) 
{ 
    if (bReverse == true) 
    { 
     m_oColReverse.Add(pFeature.OID.ToString().Trim(), pFeature.OID.ToString().Trim()); 
    } 

    if (!ContainsItem(pFeature.OID.ToString())) 
    { 
     m_oCol.Add(pFeature.OID.ToString(), new clsFeature(pFeature.OID, pFeature.ShapeCopy)); 
    } 
} 

public void AddBefore(IFeature pFeature, string strBefore, bool bReverse = false) 
{ 
    if (bReverse == true) 
    { 
     m_oColReverse.Add(pFeature.OID.ToString().Trim(), pFeature.OID.ToString().Trim()); 
    } 

    if (!ContainsItem(pFeature.OID.ToString())) 
    { 
     if (strBefore != null) 
     { 
      int index = GetIndex(m_oCol, strBefore); 

      if (index > 0) 
      { 
       m_oCol.Insert(index - 1, pFeature.OID.ToString(), new clsFeature(pFeature.OID, pFeature.ShapeCopy)); 

      } 
      else 
      { 
       m_oCol.Insert(0, pFeature.OID.ToString(), new clsFeature(pFeature.OID, pFeature.ShapeCopy)); 
      } 
     } 
    } 
} 

public void AddAfter(IFeature pFeature, string strAfter, bool bReverse = false) 
{ 
    if (bReverse == true) 
    { 
     m_oColReverse.Add(pFeature.OID.ToString().Trim(), pFeature.OID.ToString().Trim()); 
    } 

    if (!ContainsItem(pFeature.OID.ToString())) 
    { 
     if (!string.IsNullOrEmpty(strAfter)) 
     { 
      int index = GetIndex(m_oCol, strAfter); 

      m_oCol.Insert(index + 1, pFeature.OID.ToString(), new clsFeature(pFeature.OID, pFeature.ShapeCopy)); 
     } 
     else 
     { 
      m_oCol.Insert(0, pFeature.OID.ToString(), new clsFeature(pFeature.OID, pFeature.ShapeCopy)); 
     } 
    } 
} 

public int Count 
{ 
    get { return m_oCol.Count; } 
} 

public void Remove(int Id) 
{ 
    m_oCol.RemoveAt(Id); 
} 

public clsFeature Item(int Position) 
{ 
    try 
    { 
     clsFeature value = (clsFeature)m_oCol.Cast<DictionaryEntry>().ElementAt(Position).Value; 

     return value; 
    } 
    catch (Exception) 
    { 
     throw; 
    } 
} 

public void Clear() 
{ 
    m_oCol = new OrderedDictionary(); 
    m_oColReverse = new OrderedDictionary(); 
} 

public bool Reverse(string valueRenamed) 
{ 
    bool bReverse = false; 

    try 
    { 
     if (m_oColReverse.Contains(valueRenamed)) 
     { 
      return true; 
     } 
     else 
     { 
      return false; 
     } 
    } 

    catch (Exception ex) 
    { 
     if (ex is ArgumentException | ex is IndexOutOfRangeException) 
     { 
      bReverse = false; 
     } 
    } 

    return bReverse; 
} 

public bool ContainsItem(string oidValue) 
{ 
    bool bContainsItem = false; 

    string intOID = oidValue.ToString(); 

    try 
    { 
     // dictionary 
     if (m_oCol.Contains(intOID)) 
     { 
      bContainsItem = true; 
     } 
     else 
     { 
      bContainsItem = false; 
     } 

     return bContainsItem; 
    } 

    catch (Exception ex) 
    { 
     if (ex is ArgumentException | ex is IndexOutOfRangeException) 
     { 
      bContainsItem = false; 
     } 
    } 

    return bContainsItem; 
} 

public static int GetIndex(OrderedDictionary dictionary, string key) 
{ 
    for (int index = 0; index < dictionary.Count; index++) 
    { 
     if (dictionary[index] == dictionary[key]) 
     { 
      return index; 
     } 
    } 

    return -1; 
} 

// ****************************** End Ordered Dictionary - works ************************ 
+7

¿Cómo es esta una respuesta a esta pregunta? –

1

El problema es que no tiene suficientes privilegios. Aquí está una manera que funcione para mi:

RegistryKey myKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64); 
myKey = myKey.OpenSubKey(subkey, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl); 

if (myKey != null) 
{ 
    myKey.SetValue("DefaultPrinterId", ldiPrinters[e.RowIndex].id, RegistryValueKind.String); 
    myKey.Close(); 
} 

Con RegistryKey.OpenBaseKey se abra el registro correcto, porque cuando usted no tiene los permisos del registro que se escribe, lo hace en otro lugar.

Cuestiones relacionadas