Is there a way to get all namespaces you're 'using' within a class through C# code?

Is there any way to get a List<string> which contains all 'usings' within a namespace/class?

For instance

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Linq.Expressions; using System.Linq.Dynamic; using System.Text.RegularExpressions; using System.Reflection; namespace MyNamespace.Other.Scripting {

I would have a List with "System","System.Text", "System.Reflection", and so on.

EDIT: As a commented below, I'm using this http://kamimucode.com/Home.aspx/C-sharp-Eval/1 - C# evaluator, and I have to feed the TypeParser with a list of namespaces. The thing is, I won't always know which ones to put. I'm working on a simple scripting language in C# and from it I'll be able to call C# code aswell. My other alternative is create a keyword such as "using" in the scripting language, but I really don't want to do that. I want to be able to pick an C# Object, do whatever I want with it through my script.txt, and be free to use its referenced namespaces.

I want to use it in my Xna Game engine, to be able to write custom scripts which can execute C# along with my simple script functions.

-------------Problems Reply------------

This will work for all types in methods of the declaring class, however it wont give all namespaces for all classes in the file where it was before compiling. That is impossible because after compilation the framework cannot know what was where in files.

So if you have one CLASS per file this will work: If you are missing something (i look for fields and methods, maybe something is not taken in account, if that is so just add)

List<string> namespaces = new List<string>();

var m = MethodInfo.GetCurrentMethod();

foreach (var mb in m.DeclaringType.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic))
{
if (mb.MemberType == MemberTypes.Method && ((MethodBase)mb).GetMethodBody() != null)
{

foreach (var p in ((MethodInfo)mb).GetMethodBody().LocalVariables)
{
if (!namespaces.Contains(p.LocalType.Namespace))
{
namespaces.Add(p.LocalType.Namespace);
Console.WriteLine(p.LocalType.Namespace);
}
}
}
else if (mb.MemberType == MemberTypes.Field) {
string ns = ((System.Reflection.FieldInfo)mb).FieldType.Namespace;
if (!namespaces.Contains(ns))
{
namespaces.Add(ns);
Console.WriteLine(ns);
}
}
}

Sample output for my case:

System
System.Collections.Generic
System.Reflection
WindowsFormsApplication2
System.Linq.Expressions

Here's a rough untested attempt to get you started:

IEnumerable<string> GetNamespacesUsed(string fileName)
{
var lines = System.IO.File.ReadAllLines(fileName);
var usingLines = lines.Where(
x => x.StartsWith("using ") && !x.StartsWith("using ("));

foreach (var line in usingLines)
{
if (line.Contains("="))
yield return line.Substring(line.IndexOf("="), line.Length - 1);
else
yield return line.Substring(line.Length - 1);
}
}

The line.Length - 1 may not be correct to cut off the semicolon on the end. You'll need to test it to find out what it should be. Also, this assumes your code is formatted in a fairly standard way. If it's not, it won't work.

You can use Mono Cecil to read a class definition from an assembly and get a list of all the referenced types in each method. From there, you can extract a list of namespaces (fully qualified type name minus the last part).

Category:c# Views:0 Time:2011-04-28

Related post

  • Is there Any Way to Set the Namespace of a Web Service in Configuration instead of Code? 2010-06-16

    Currently we're using in code <System.Web.Services.WebService(Namespace:="https://ourservice/")> to set the namespace, can this be done in web.config, instead? I've looked but can't find where? VS2008, ASMX web service. --------------Solutions-

  • Opening a namespace in F#.net for a specific block of code 2012-04-25

    I understand this is not possible in C#; the nearest thing is to form an alias at the top of the code file. Is there a way to do this in F#? See this question for the C# analogue of my question: My guess is "No, use an alias." but nothing ventured, n

  • Should 'using' statements be inside or outside the namespace? 2008-09-24

    I have been running StyleCop over some C# code, and it keeps reporting that my using statements should be inside the namespace. Is there a technical reason for putting the using statements inside instead of outside the namespace? --------------Soluti

  • Using - inside namespace or outside namespace 2008-09-24

    I have been running StyleCop over some C# code, and it keeps reporting that my using statements should be inside the namespace. Is there a technical reason for putting the using statements inside instead of outside the namespace? --------------Soluti

  • XML namespace problem in Visual Studio generated service reference 2008-09-25

    I'm connecting to a web service hosted by a third-party provider. I've added a service reference in my project to the web service, VS has generated all the references and classes needed. I'm connecting with this piece of code (client name and methods

  • Do you prefer explicit namespaces or 'using' in C++? 2008-10-18

    When using C++ namespaces, do you prefer to explicitly name them, like this: std::cout << "Hello, world!\n"; Or do you prefer using namespace: using namespace std; cout << "Hello, world!\n"; And if if you prefer the latter, do you declare

  • Why can't I use the 'AccessDeniedException' namespace? 2008-11-17

    I get the message that the namespace can't be found when I use the code below. Where does the AccessDeniedException live? try { ... } catch (SomeKindOfException ex) { MessageBox.Show(ex.Message); } catch (AccessDeniedException ex) { //Do something el

  • Does it matter if I include more references and namespaces in a class 2009-01-05

    For example: using System; using System.Web; using System.Collections; using System.Web.Services; using System.Web.Services.Protocols; using System.Web.Script.Serialization; using System.Web.Script.Services; using System.Web.Security; using System.Da

  • NET: Best Practices/guidelines for dividing namespaces between files? 2009-01-26

    What should be the general guidelines/gotchas for dividing application code (App_Code) into separate files? I've found that over time, the original files do not match up well with how the namespace hierarchy evolves. How do I keep application code co

  • Organizing classes into namespace in the App_Code folder not working as expected 2009-02-06

    I have a couple of classes that I have created for my web project and I am going to store them in the App_Code folder. I don't want to store all the classes in the top level (no namespace) but want to organize them into namespaces. So far this does n

  • How do you ensure .Net always searches for a namespace from the root of the namespace tree? 2009-02-12

    Is there a way to tell .Net to search for a namespace from the root of the namespace tree? Say I have these two, completely independent, namespaces: Apple.Orange.Banana Orange.Grape.Peach Assume they came from different programmers and the "Orange" i

  • XML-documentation for a namespace 2009-04-27

    Would you write xml-doc for a namespace? And if yes, how and where? I would think, if it is possible, maybe an almost empty file like this: /// <summary> /// This namespace contains stuff /// </summary> namespace Some.Namespace { } But wi

  • How to comment a namespace 2009-04-27

    Would you write xml-doc for a namespace? And if yes, how and where? I would think, if it is possible, maybe an almost empty file like this: /// <summary> /// This namespace contains stuff /// </summary> namespace Some.Namespace { } But wi

  • Move a list of source files with classes inside to another folder and automatically change namespace 2009-05-19

    Let's say I have 100 winforms in folder Forms. All form classes belong to ProjectName.Forms namespace. I want to move all those forms to folder WinForms and I want their namespace to change to ProjectName.WinForms. Is there a way to do this automatic

  • How to remove all namespaces from XML with C#? 2009-06-12

    I am looking for the clean, elegant and smart solution to remove namespacees from all XML elements? How would function to do that look like? Defined interface: public interface IXMLUtils { string RemoveAllNamespaces(string xmlDocument); } Sample XML

  • use svcutil to map multiple namespaces for generating wcf service proxies 2009-07-09

    I want to use svcutil to map multiple wsdl namespace to clr namespace when generating service proxies. I use strong versioning of namespaces and hence the generated clr namespaces are awkward and may mean many client side code changes if the wsdl/xsd

  • (ASP.NET) Automatic way to put all code-behind classes in a namespace 2009-07-11

    I just converted a WebSite to a Web application and put in a new namespace. I now need to put all code behind files in this namespace. is there an automatic way to do it or am I going to have to go to each page and do it manually? --------------Solut

  • private/public class in namespace problem 2009-07-19

    This is a question about what defining a class as public or private does. Right now, I have various classes defined inside of a namespace and I only want some of those classes to be visible/usable to the outside world. So, for example, if the classes

  • Visual studio 2008 dataset generation issue (namespace issue) 2009-07-28

    At work we use typed dataset in some projects for our DataAccess layer. Sometimes we extend them using the partial class feature : using View code on a dataset create a DataSetName.cs with the partial class declaration where you can add code. Inside

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.077 (s). 11 q(s)