How to merge source code files

On this page


GroupDocs.Comparison allows you to merge source code files by using the ComparisonAction properties:

To apply/reject changes to output file, follow these steps:

  1. Instantiate the Comparer object. Specify the source document path or stream.
  2. Call the add() method. Specify the target document path or stream.
  3. Call the compare() method.
  4. Call the getChanges() method to get changes list.
  5. Call the setComparisonAction() method of the appropriate change object. Specify the ComparisonAction.ACCEPT or the ComparisonAction.REJECT value.
  6. Call the applyChanges() method. Specify the collection of changes.

For example, you need to compare and merge several versions of source code files and to accept or discard changes made by different persons.

The differences show that two methods are in the source.cs file: AddNumbers and Sum.

If you do not use the ComparisonAction property, all changes are committed to the output file, and these methods are removed. If you need to control the merging of files, the ComparisonAction property helps you.

The following code snippet shows how to merge two source code files:

try (Comparer comparer = new Comparer(sourcePath)) {
    comparer.add(targetPath);
    final Path resultPath = comparer.compare(outputPath);

    ChangeInfo[] changes = comparer.getChanges();
    for (int i = 0; i < 10; i++) {
        changes[i].setComparisonAction(ComparisonAction.ACCEPT);
    }

    for (int i = 10; i < changes.length; i++) {
    	changes[i].setComparisonAction(ComparisonAction.REJECT);
    }

    comparer.applyChanges(resultPath, new ApplyChangeOptions(changes));
}

As a result, you get a merged source code file where the deleted elements are marked in red, the added – in blue, and the modified – in green.

Also you receive an HTML file in HTML with changed places in the code.

Result source code fileResult HTML file

As you can see from the resulting files, only one of the two methods was removed.

On this page