Dateipfad eines TwinCAT-Projekts ermitteln
Dieses Kapitel zeigt zwei Wege, um den Dateipfad eines TwinCAT-Projekts zu ermitteln:
- Pfad zur
.tsproj-Datei einer TwinCAT-Solution über das DTE-Project-Objekt. - Pfad zur
.plcproj-Datei einzelner PLC-Projekte überProduceXmlauf dem PLC-Knoten.
Pfad zur .tsproj-Datei über DTE
SolutionBuild.BuildProject benötigt den Dateipfad des TwinCAT-Projekts. Dieser lässt sich über die FileName-Eigenschaft des DTE-Project-Objekts ermitteln.
C#:
EnvDTE.DTE dte = (EnvDTE.DTE)Marshal.GetActiveObject("TcXaeShell.DTE.17.0");
foreach (EnvDTE.Project project in dte.Solution.Projects)
{
// FileName returns the full path to the .tsproj file
string projectPath = project.FileName;
Console.WriteLine(projectPath);
// Output e.g.: C:\Projects\MyProject\MyProject.tsproj
}PowerShell:
$dte = [Runtime.InteropServices.Marshal]::GetActiveObject("TcXaeShell.DTE.17.0")
foreach ($project in $dte.Solution.Projects) {
$projectPath = $project.FileName
Write-Host $projectPath
}
# For use with SolutionBuild.BuildProject
$dte.Solution.SolutionBuild.BuildProject(
"Debug|TwinCAT RT (x64)", # ConfigurationName
$projectPath, # ProjectUniqueName (FileName or UniqueName)
$true # WaitForBuildToFinish
)Pfad zur .plcproj-Datei über ProduceXml
Der Pfad zur .plcproj-Datei eines PLC-Projekts ist nicht direkt über DTE zugänglich. Stattdessen wird der PLC-Knoten TIPC iteriert und der ProjectPath-Wert aus der XML jedes PLC-Kindobjekts ausgelesen.
ITcSmTreeItem plcNode = sysMan.LookupTreeItem("TIPC");
// Dictionary [key = project name | value = project file path]
Dictionary<string, string> projectPaths = [];
int padWidth = plcNode.ChildCount.ToString().Length;
int maxNameLength = Enumerable.Range(1, plcNode.ChildCount).Max(i => plcNode.Child[i].Name.Length);
// Iterate through all PLC projects and extract their project paths and names
for (int i = 1; i <= plcNode.ChildCount; i++)
{
var child = plcNode.Child[i];
var doc = XDocument.Parse(child.ProduceXml());
string projectPath = doc.Descendants("ProjectPath").FirstOrDefault()?.Value ?? "Unknown";
projectPaths.Add(child.Name, projectPath);
Console.WriteLine($"{i.ToString().PadLeft(padWidth)}: Project Name: {child.Name.PadRight(maxNameLength)}, Project Path: {projectPath}");
}