سؤال

I found class name validation method using CodeDOM from SE and I used it:

System.CodeDom.Compiler.CodeGenerator.IsValidLanguageIndependentIdentifier(string value)

through this link:Is there a .NET function to validate a class name?

But, class names don't allow '.' (OEM period) where namespaces can be something like: System.Linq for example which allows '.'. Before going for options like Regex or loops for validating namespace names, I like to know whether there are any methods in .NET for this task.

EDIT:

Actual scenario is, I have a from. User can give a class name and a namespace from textboxes. For that class name and namespace I'll give a generated code. If user entered SomeClass as class name and Some.Namespace for namespace then the generated code will be:

namespace Some.Namespace   
{   
  class SomeClass{}   
}

For that i need to validate those two names user entering.

هل كانت مفيدة؟

المحلول

I have tried a different approach and it works for me.

public bool IsValidNamespace(string input)  
        {  
            //Split the string from '.' and check each part for validity  
            string[] strArray = input.Split('.');  
            foreach (string item in strArray)  
            {                  
                if (! CodeGenerator.IsValidLanguageIndependentIdentifier(item))  
                    return false;  
            }  
            return true;   
        }

نصائح أخرى

You can use CodeGenerator.ValidateIdentifiers() for that.

If you don't want to check your whole tree, just one namespace name, you can create a temporary object for that:

CodeGenerator.ValidateIdentifiers(new CodeNamespace(namespaceName));

Per the documentation, if the identifier isn't valid, the method will throw ArgumentException.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top