How to merge source code files


GroupDocs.Comparison provides an ability to merge source code files by using the ComparisonAction properties:

The following are the steps to apply/reject changes to resultant file.

Example of merge source code file by using GroupDocs.Comparison


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

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

If you did not use ComparisonAction, then in the resulting file, all changes will be committed, and these methods will be removed, but if you need to control the merging of files, the ComparisonAction property will help you with this.

Example of using ComparisonAction


The following code samples demonstrate how to merge two source code files.

using (Comparer comparer = new Comparer(sourcePath))
{
    comparer.Add(targetPath);
    comparer.Compare(resultPath);

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

    for (int i = 10; i < changes.Length; i++)
    {
    	changes[i].ComparisonAction = ComparisonAction.Reject;
    }

    comparer.ApplyChanges(File.Create(resultPath), new ApplyChangeOptions { Changes = changes });
}

The result of merging files


As a result, we 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 will receive a file in HTML format 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.

More resources


GitHub Examples

You may easily run the code above and see the feature in action in our GitHub examples:

Free Online App

Along with full-featured .NET library we provide simple, but powerful free Apps.
You are welcome to compare your DOC or DOCX, XLS or XLSX, PPT or PPTX, PDF, EML, EMLX, MSG and other documents with free to use online GroupDocs Comparison App.