コード例 #1
0
 /// <summary>
 /// 根据文件字符串创建项目项
 /// </summary>
 /// <param name="project"></param>
 /// <param name="fileString">文件字符串内容</param>
 /// <param name="itemName">文件名称(包括后缀)</param>
 /// <param name="encoding">编码方式</param>
 /// <returns>创建完成的项目项</returns>
 public static ProjectItem AddFromFileString(this Project project, string fileString, string itemName, Encoding encoding)
 {
     try
     {
         //创建项文件
         string filePath = Path.Combine(project.GetDirectory(), itemName);
         using (FileStream create = new FileStream(filePath, FileMode.OpenOrCreate))
         {
             byte[] buffer = encoding.GetBytes(fileString);
             create.Write(buffer, 0, buffer.Length);
         }
         //添加项文件到项目中
         ProjectItem projectItem = project.ProjectItems.FindItem(itemName);
         if (null != projectItem)
         {
             projectItem.Remove();
         }
         projectItem = project.ProjectItems.AddFromFile(filePath);
         if (null == projectItem)
         {
             projectItem = project.ProjectItems.FindItem(itemName);
         }
         projectItem.FormatDocument();
         return(projectItem);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }