Lem*_*urr 5 c# visual-studio vsix visual-studio-extensions
我正在创建一个VS扩展,我想在解决方案中添加一个文件并设置一些属性.其中一个是Copy to output directory,但我找不到设置它的方法.设置Build action工作正常,但调试时甚至没有在数组中列出所需的属性.
private EnvDTE.ProjectItem AddFileToSolution(string filePath)
{
var folder = CurrentProject.ProjectItems.AddFolder(Path.GetDirectoryName(filePath));
var item = folder.ProjectItems.AddFromFileCopy(filePath);
item.Properties.Item("BuildAction").Value = "None";
// item.Properties.Item("CopyToOutputDirectory").Value = "CopyAlways"; // doesn't work - the dictionary doesn't contain this item, so it throws an exception
return item;
}
Run Code Online (Sandbox Code Playgroud)
如何为新添加的项目设置属性?
对于 C# 或 VB 项目,Cole Wu - MSFT 的答案应该有效。
如果您尝试对不同类型的项目执行相同的操作,那么您可能会运气不佳,因为每种项目类型都有不同的属性。
根据我的尝试:
查看您尝试修改的项目中文件的属性窗口。它是否包含“CopyToOutputDirectory”属性?如果不是,则该属性可能不可用。
编辑:
设置 ProjectItem 属性的另一个选项是通过它的属性(在 *.csproj 中修改它)。我想说这是解决方法,而不是真正的解决方案,因为您之后需要重新加载项目。
private EnvDTE.ProjectItem AddFileToSolution(string filePath)
{
var folder = CurrentProject.ProjectItems.AddFolder(Path.GetDirectoryName(filePath));
var item = folder.ProjectItems.AddFromFileCopy(filePath);
item.Properties.Item("BuildAction").Value = "None";
// Setting attribute instead of property, becase property is not available
SetProjectItemPropertyAsAttribute(CurrentProject, item, "CopyToOutputDirectory", "Always");
// Reload project
return item;
}
private void SetProjectItemPropertyAsAttribute(Project project, ProjectItem projectItem, string attributeName,
string attributeValue)
{
IVsHierarchy hierarchy;
((IVsSolution)Package.GetGlobalService(typeof(SVsSolution)))
.GetProjectOfUniqueName(project.UniqueName, out hierarchy);
IVsBuildPropertyStorage buildPropertyStorage = hierarchy as IVsBuildPropertyStorage;
if (buildPropertyStorage != null)
{
string fullPath = (string)projectItem.Properties.Item("FullPath").Value;
uint itemId;
hierarchy.ParseCanonicalName(fullPath, out itemId);
buildPropertyStorage.SetItemAttribute(itemId, attributeName, attributeValue);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
874 次 |
| 最近记录: |