Reading the default namespace through Roslyn API

北城余情 提交于 2019-12-02 00:52:11

Unfortunately, Roslyn does not expose a way to do that at the moment, but I agree that it is something we will probably need eventually.

The library Microsoft.Build.Evaluation, which is, I believe, the successor of Roslyn does have this feature, but it is not easy to find.

I use the code below to obtain the default namespace.

My tests have shown that it matches the RootNamespace, stored in the .csproj file.

        private string GetDefaultNamespace(Microsoft.Build.Evaluation.Project p)
    {
        string rtnVal = "UNKNOWN_NAMESPACE";

        foreach (ProjectItemDefinition def in p.ItemDefinitions.Values)
        {
            if (def.ItemType == "ProjectReference")
            {
                foreach(ProjectProperty prop in def.Project.AllEvaluatedProperties){
                    if(prop.Name == "RootNamespace"){
                        rtnVal = prop.EvaluatedValue;
                    }
                }
            }
        }

        return rtnVal;
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!