How do I add a "using System;" statement to a c# file?
It looks like the UsingUtil class is helpful for achieving this, however every ReSharper implementation of IUsingDirective is marked as internal. How do I create a new IUsingDirective? Do I have to create my own implementation?
Any pointers?
Cheers
Please sign in to leave a comment.
Solved. This did the trick:
/// /// Ensures the namespace exists. /// /// The file. /// Name of the namespace.]]>
public static void EnsureNamespaceExists(ICSharpFile file, String namespaceName)
{
Boolean namespaceExists = false;
String usingStatement = String.Format(CultureInfo.InvariantCulture, "using {0};", namespaceName);
// Loop through the existing imports
foreach (IUsingDirective directive in file.Imports)
{
// Check if the using directive is the one we are looking for
if (directive.GetText() == usingStatement)
{
// The namespace is already imported.
namespaceExists = true;
break;
}
}
// Check if the namespace already exists
if (namespaceExists == false)
{
// We need to add the namespace
// Create the new using statement
IUsingDirective directive =
CSharpElementFactory.GetInstance(file.GetProject()).CreateUsingDirective(namespaceName, null);
// Add it to the file
UsingUtil.AddImportTo(file, directive);
}
}
Edited by: Rory Primrose on Jul 4, 2008 2:30 PM
It is incorrect to compare using's by their text (because of different
formatting, comments, and so on).
Better way is try to cast IUsingDirective to IUsingNamespaceDirective and
then get the imported namespace
--
Eugene Pasynkov
Developer
JetBrains, Inc
http://www.jetbrains.com
"Develop with pleasure!"
"Rory Primrose" <no_reply@jetbrains.com> wrote in message
news:33385788.83791215145846371.JavaMail.jive@app4.labs.intellij.net...
>
>
>
>
>
>
>
Thanks Eugene. The function now looks like this:
/// /// Ensures the namespace exists. /// /// The file. /// Name of the qualified namespace.]]>
public static void EnsureNamespaceExists(ICSharpFile file, String qualifiedNamespaceName)
{
Boolean namespaceExists = false;
// Loop through the existing imports
foreach (IUsingDirective directive in file.Imports)
{
IUsingNamespaceDirective namespaceDirective = directive as IUsingNamespaceDirective;
// We we could convert the type, skip to the next item
if (namespaceDirective == null
|| namespaceDirective.ImportedNamespace == null)
{
continue;
}
// Check if the using directive is the one we are looking for
if (namespaceDirective.ImportedNamespace.QualifiedName == qualifiedNamespaceName)
{
// The namespace is already imported.
namespaceExists = true;
break;
}
}
// Check if the namespace already exists
if (namespaceExists == false)
{
// We need to add the namespace
// Create the new using statement
IUsingDirective directive =
CSharpElementFactory.GetInstance(file.GetProject()).CreateUsingDirective(qualifiedNamespaceName, null);
// Add it to the file
UsingUtil.AddImportTo(file, directive);
}
}