How to merge source code files
Leave feedback
On this page
GroupDocs.Comparison allows you to merge source code files by using the ComparisonAction properties:
- ComparisonAction.Accept accepts the found changes and adds them to the file without highlighting
- ComparisonAction.Reject rejects the found changes and removes them from the output file
To apply/reject changes to output file, follow these steps:
- Instantiate the Comparer object. Specify the source document path or stream.
- Call the Add method. Specify the target document path or stream.
- Call the Compare method.
- Call the GetChanges method to get changes list.
- Set the ComparisonAction of the appropriate change object to the ComparisonAction.Accept or ComparisonAction.Reject value;
- 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:
using GroupDocs.Comparison;
using GroupDocs.Comparison.Result;
using GroupDocs.Comparison.Options;
using System.IO;
// ...
using (Comparer comparer = new Comparer("source.docx"))
{
comparer.Add("target.docx");
comparer.Compare("result.docx");
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("result.docx"), new ApplyChangeOptions { Changes = 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 file | Result HTML file |
---|---|
As you can see from the resulting files, only one of the two methods was removed.
Was this page helpful?
Any additional feedback you'd like to share with us?
Please tell us how we can improve this page.
Thank you for your feedback!
We value your opinion. Your feedback will help us improve our documentation.