Search code examples
c#kmlgoogle-earthkmz

Create KMZ file from KML file Programatically in C#


I have a number of kml file I am generating in a directory.

I am wondering if there is a way to group them all into a kmz file programmatically in C#. With a name and description displayed in google earth.

Thanks and best regards,

private static void combineAllKMLFilesULHR(String dirPath)
{
    string kmzPath = "outputULHR.kmz";

    string appPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
    string rootKml = appPath + @"\" + dirPath + @"\doc.kml";
    Console.WriteLine(appPath + @"\"+ dirPath);
    String[] filepaths = Directory.GetFiles(appPath + @"\" + dirPath);

    using (ZipArchive archive = ZipFile.Open(kmzPath, ZipArchiveMode.Create))
    {
        archive.CreateEntryFromFile( rootKml, "doc.kml");
        foreach (String file in filepaths)
        {
            Console.WriteLine(file);
            if(!file.Equals(rootKml))
                archive.CreateEntryFromFile( file, Path.GetFileName(file) );
        }
    }
}

Solution

  • Being a KMZ file a zip archive, you can use the ZipArchive class to generate it.

    string kmzPath = "output.kmz";
    string rootKml = "doc.kml";
    string referencedKml = "someother.kml";
    
    using (ZipArchive archive = ZipFile.Open(kmzPath, ZipArchiveMode.Create))
    {
        archive.CreateEntryFromFile(rootKml, "doc.kml");
        archive.CreateEntryFromFile(referencedKml, "someother.kml");
    } 
    

    just remember to name the default kml as doc.kml, from the documentation:

    Put the default KML file (doc.kml, or whatever name you want to give it) at the top level within this folder. Include only one .kml file. (When Google Earth opens a KMZ file, it scans the file, looking for the first .kml file in this list. It ignores all subsequent .kml files, if any, in the archive. If the archive contains multiple .kml files, you cannot be sure which one will be found first, so you need to include only one.)