Elmo
Elmo

Reputation: 6471

Saving File Paths as Sub Key in Registry

I am currently saving filepaths to a subkey in the Windows Registry like this:

Registry.SetValue(String.Format("HKEY_CURRENT_USER\Software\MyApp\{0}\{1}\{2}\{3}", FilePath.Replace("\", "/"), x, y, z), SettingName, SettingValue)

Since the Windows Registry doesn't accept the char \ in the sub-key name, I am replacing it with /.

So I was wondering if this is okay and if there are any other characters that a file name can have but a subkey name cannot have?

Upvotes: 1

Views: 1631

Answers (2)

Nick Pearce
Nick Pearce

Reputation: 758

Backslash is the only character not allowed. See this post

To answer your implied question as to whether this is OK: it might be more elegant to store the whole file path as a string value in a key. If you have a need to represent the file structure in the key name itself then your approach is probably the cleanest.

Upvotes: 2

Soner Gönül
Soner Gönül

Reputation: 98770

I don't think so it is ok. I didn't tried it but it couldn't work. Try like this;

Registry.SetValue(String.Format("HKEY_CURRENT_USER\\Software\\MyApp\\{0}\\{1}\\{2}\\{3}", x, y, z), SettingName, SettingValue);

\\ is a special character. For example, if you try;

Console.WriteLine("\");

compiler gives you an error. But if you write \ as an output, you do like;

Console.WriteLine("\\");

As you can see, it is not a registry issue. C# defines the following character escape sequences, look at MSDN:

  • \' - single quote, needed for character literals
  • \" - double quote, needed for string literals
  • \\ - backslash
  • \0 - Unicode character 0
  • \a - Alert (character 7)
  • \b - Backspace (character 8)
  • \f - Form feed (character 12)
  • \n - New line (character 10)
  • \r - Carriage return (character 13)
  • \t - Horizontal tab (character 9)
  • \v - Vertical quote (character 11)
  • \uxxxx - Unicode escape sequence for character with hex value xxxx
  • \xn[n][n][n] - Unicode escape sequence for character with hex value nnnn (variable length version of \uxxxx)
  • \Uxxxxxxxx - Unicode escape sequence for character with hex value xxxxxxxx (for generating surrogates)

Also read Structure of the Registry

Each key has a name consisting of one or more printable characters. Key names are not case sensitive. Key names cannot include the backslash character (), but any other printable character can be used. Value names and data can include the backslash character.

Upvotes: 1

Related Questions