享受生活,享受学习

导航

生成代码自动加入到解决方案中


在开发时或者开发生成工具时,我们有定义的框架 ,然后把生成的代码直接加入到解决方案中,解决方案自动更新。

解决方法:
   把生成文件的放入解决方案的对应项目目录,同时更改项目文件,如在类库项目更新 “.csproj”,把生成的文件及路径写入     <ItemGroup> <Compile Include="newnew.cs"  />  </ItemGroup> 中。项目加载时就可以加载文件了。而在Website中不需要加到项目文件中,但WEB应用程序则需要.
用XmlDocument来更改项目文件。

       /// <summary>
        /// 更改解决方案的项目文件
        /// </summary>
        /// <param name="slnPath"></param>
        /// <param name="fileName"></param>
        /// <param name="ifWebsite"></param>
        public void UpdateProjectFile(string slnPath, string slnName,string fileName, bool ifWebsite)
        {

            if (ifWebsite == true)
                return;
            //解决方案名称
            string objName = slnPath + "/" + slnName + "." + bizProjectName + "/" + slnName + "." + bizProjectName + ".csproj";

            if (File.Exists(objName))
            {

                System.Xml.XmlDocument doc = new XmlDocument();
                doc.Load(objName);
                string nameSpace = doc.DocumentElement.Attributes["xmlns"].Value.Trim();
                foreach (XmlNode xmlNode in doc.DocumentElement.ChildNodes)
                {
                    if (xmlNode.NodeType == XmlNodeType.Element)
                    {
                        XmlElement xmlFirstElement = (XmlElement)xmlNode;
                        if (xmlFirstElement.Name == "ItemGroup" && xmlFirstElement.FirstChild.Name == "Compile")
                        {
                            XmlElement newXmlE = doc.CreateElement("", "Compile", nameSpace);
                            newXmlE.SetAttribute("Include", fileName);
                            xmlFirstElement.AppendChild(newXmlE);
                        }
                    }
                }
                doc.Save(objName);
            }
        }
       
    注意:
 
XmlDocument CreateElement时,会自动添加 xmlns="" 的属性,结果为: <Compile Include="newnew.cs" xmlns="" />
这是因为没有声明命名空间,可将这个节点的xmlns,设为与整个文件的相同,则xmlns将不出现.

                            XmlElement newXmlE = doc.CreateElement("Compile");
                            newXmlE.SetAttribute("Include", fileName);
                            xmlFirstElement.AppendChild(newXmlE);
改成了                
                            XmlElement newXmlE = doc.CreateElement("", "Compile", doc.DocumentElement.Attributes["xmlns"].Value);
                            newXmlE.SetAttribute("Include", fileName);
                            xmlFirstElement.AppendChild(newXmlE);


 

posted on 2007-09-27 12:03  徘徊中的海鸟  阅读(252)  评论(0编辑  收藏  举报