18

The msdn documentation says add namespaces imports to the CodeNamespace.Imports collection. This puts them inside the namespace (which makes sense, since your adding them to the namespace)

namespace Foo
{
  using Bar;

  //Code
}

However the rest of our code base has using statements outside the namespace:

using Bar;

namespace Foo
{
  //Code
}

Is there a clean way to get CodeDom to emit the second version?

Edit: the code to produce the first example looks something like this:

CodeNamespace ns = new CodeNamespace("Foo");
ns.Imports.Add(new CodenamespaceImport("Bar"));
CodeCompileUnit cu = new CodeCompileUnit();
cu.Namespaces.Add(ns);
new CSharpCodeProvider().GenerateCodeFromCompileUnit(cu, Console.Out, null);
Josh Sterling
  • 838
  • 7
  • 12

2 Answers2

23

The simplest way is to add a global namespace entry into the Compile Unit (namespace without a name) and add the imports to it.

Hamid62
  • 183
  • 4
  • 15
Thomas Mittag
  • 246
  • 3
  • 3
  • thank you; I had been wondering about this... a heartfelt +1 for the Frankenanswer, and also +1 for the spoooooky necrocomment praising the necro answer. :) and +♥♥ since it's the right time for spooky necro stuff and Frankenthings. ;) – shelleybutterfly Oct 31 '12 at 07:50
8

So the code would be the same as before but with this bit added in.

CodeNamespace globalNamespace = new CodeNamespace();
globalNamespace.Imports.Add(new CodeNamespaceImport("Foo"));

// globalNamespace.Comments = string.Empty;    you cannot do this
ccu.Namespaces.Add(globalNamespace);
ccu.Namespaces.Add(ns);
Brian
  • 81
  • 1
  • 2