开发者

Getting an unexpected "?" at the end of a Registry GetValue

I use the Registry class to manage values in the Registry on Windows Seven in C#.

Registry.GetValue(...);

But, I'm facing a curious behavi开发者_如何学Cor : Every time, the returned value is the correct one, but sometimes, it is followed by an unexpected "?"

When I check the Registry, (regedit), the "?" doesn't exist. I really don't understand from where this question mark come from.

Info :

  • C#
  • 3.5 framework
  • windows 7 64 bits (and i want my application to work on both 32 and 64 bits systems)


That didn't quite work for me, I was also getting a random ? at the end of a value from the registry that was a file path. It only appeared every now and again. It seems like a bug.

I use 2 pass method to see if directory exists and then strip out characters, I was getting unicode character 1792 at the end. < 128 probably won't work for some languages.

string configPath = val.ToString();
bool dirExists = false;
if (Directory.Exists(configPath))
{
    dirExists = true;
}
else
{

    _logger.Warn("The path for service {0} doesn't exist: {1}", serviceName, configPath);

    StringBuilder configPathBuilder = new StringBuilder(configPath.Length);

    // Do this to remove any dodgy characters in the path like a ? at end
    char[] inValidChars = Path.GetInvalidPathChars();
    foreach (Char c in configPath.ToCharArray())
    {
        if (inValidChars.Contains(c) == false && c < 128)
        {
            configPathBuilder.Append(c);
        }
        else
        {
            _logger.Warn("An invalid path was character was found in the path: {0} {1}", c, (int)c);
        }
    }

    configPath = configPathBuilder.ToString();

    if (Directory.Exists(configPath))
    {
        dirExists = true;
    }

}


So my question is, "who set the value"?

Perhaps whoever did the setting put in an unprintable character at the end of the string. It is probably not actually a question mark. This may be a result of a bug in the program which did the setting, not anything to do with your code, per se.


I found a way to remove the unexpected char, thanks to all your comments ;)

 String value = null;
        try
        {
            foreach (Char item in Registry.GetValue(registryKey, key, "").ToString().ToCharArray())
            {
                if (Char.GetUnicodeCategory(item) != System.Globalization.UnicodeCategory.OtherLetter && Char.GetUnicodeCategory(item) != System.Globalization.UnicodeCategory.OtherNotAssigned)
                {
                    value += item;
                }
            }
        }
        catch (Exception ex)
        {
            LOG.Error("Unable to get value of " + key + ex, ex);
        }
        return value;

I made some tests to know what kind of char appears from time to time. It was, just like you said Larry, an unicode problem. I still don't understand why this char appears sometimes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜