Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
470 views
in Technique[技术] by (71.8m points)

c# - How to programmatically include a file in my project?

Background

I'm making a helper application that reformats some code files and creates new code files, which are to be added to my other project, so I could use the new code right away, but I'm having serious trouble adding that new code file into my project automatically. By the way it's in c# and the helper app is WinForms.

Failed attempts

This question's only answer has two ways of doing that, but I couldn't make any of them work. With the first I can't find a Microsoft.Build assembly to reference, and in the other there are clearly not enough arguments for a command line.

Question

How do I programmatically include a file into a project without the use of third-party applications?

Basically, I'm looking for the equivalent of this:

...But done using code.

Requirements

These are the features I suppose the solution should offer:

  • Select the solution which has the project we're adding the file to
  • Select project into which the file is to be added
  • Select directory within the project
  • And, of course, the file which we're adding

Progress

With user @psubsee2003's help I was able to find the Microsoft.Build.dll file in C:WindowsMicrosoft.NETFrameworkv4.0.30319 folder on my computer and successfully import it by changing my project's target framework to version 4 Full profile, not the default Client profile.

And I found how to use the AddItem method:

var p = new Microsoft.Build.Evaluation.Project(@"C:projectsMyProject.csproj");
p.AddItem("Compile", @"C:folderfile.cs");
p.Save();

The file will appear in project's root folder unless the project already had a folder called folder, in which case the file will be placed there. So basically the file will be placed in the deepest folder chain found in the original file's path going towards the root folder.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It worked for my just adding the it to the ProjectFolder, and also add the folder programmatically like this.

var p = new Microsoft.Build.Evaluation.Project(@"C:projectsBabDbestest.csproj");
        p.AddItem("Folder", @"C:projectsBabDbestest2");
        p.AddItem("Compile", @"C:projectsBabDbestest2Class1.cs");
        p.Save();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...