Home > Code Samples > How to add a file that depends upon another file

How to add a file that depends upon another file

October 23rd, 2010

Note, this article has been moved to the official DevExpress Support Center site. Please refer to the moved article as it might have further updates or additional comments. Thank you.

To programmatically add a file to a specific project that depends upon another file (DependentUpon), you can use methods from the DXCore Solution service.

Consider the following solution structure:

DXCore Solution Explorer structure sample

Here, you will add the Class2.cs file into the ClassLibrary1 project that depends on the Class1.cs file. Here’s a sample on how to achieve this:

CSharp code:

EnvDTE.Project targetProject = CodeRush.Solution.FindEnvDTEProject("ClassLibrary1");
if (targetProject != null)
{
  string projectPath = Path.GetDirectoryName(targetProject.FileName);
  string dependantFilePath = Path.Combine(projectPath, "Class2.cs");

  EnvDTE.ProjectItem targetFileProjectItem = CodeRush.Solution.FindProjectItemByName(targetProject, "Class1.cs");
  if (targetFileProjectItem != null)
  {
    targetFileProjectItem.ProjectItems.AddFromFile(dependantFilePath);
  }
}

Visual Basic code:

Dim targetProject As EnvDTE.Project = CodeRush.Solution.FindEnvDTEProject("ClassLibrary1")
If targetProject IsNot Nothing Then
  Dim projectPath As String = Path.GetDirectoryName(targetProject.FileName)
  Dim dependantFilePath As String = Path.Combine(projectPath, "Class2.cs")

  Dim targetFileProjectItem As EnvDTE.ProjectItem = CodeRush.Solution.FindProjectItemByName(targetProject, "Class1.cs")
  If targetFileProjectItem IsNot Nothing Then
    targetFileProjectItem.ProjectItems.AddFromFile(dependantFilePath)
  End If
End If

Note that the dependent file must be located in the same folder where the parent file is located.

After that, you will see the new file added into the project:

DXCore Solution Explorer new dependant file added

—–
Products: DXCore
Versions: 12.1 and up
VS IDEs: any
Updated: Oct/31/2012
ID: D028

Similar Posts: