-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathCreateKmz.cs
More file actions
86 lines (75 loc) · 2.84 KB
/
CreateKmz.cs
File metadata and controls
86 lines (75 loc) · 2.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using System;
using System.IO;
using SharpKml.Engine;
namespace Examples
{
/// <summary>
/// Creates a Kmz archive from the specified Kml file.
/// </summary>
public static class CreateKmz
{
public static void Run()
{
const string OutputPath = "output.kmz";
string input = Program.GetInputFile("Enter a file to convert to Kmz:", "Data/doc.kml");
try
{
KmlFile kml = LoadKml(input);
using (KmzFile kmz = SaveKmlAndLinkedContentIntoAKmzArchive(kml, input))
using (Stream output = File.Create(OutputPath))
{
kmz.Save(output);
Console.WriteLine("Saved to '{0}'.", OutputPath);
}
// Now open the file we saved and list the contents
using (Stream file = File.OpenRead(OutputPath))
using (KmzFile kmz = KmzFile.Open(file))
{
Console.WriteLine("Contents:");
foreach (string name in kmz.Files)
{
Console.WriteLine(name);
}
}
}
catch (Exception ex)
{
Program.DisplayError(ex.GetType() + "\n" + ex.Message);
}
}
private static KmlFile LoadKml(string path)
{
using (Stream file = File.OpenRead(path))
{
return KmlFile.Load(file);
}
}
private static KmzFile SaveKmlAndLinkedContentIntoAKmzArchive(KmlFile kml, string path)
{
// All the links in the KML will be relative to the KML file, so
// find it's directory so we can add them later
string basePath = Path.GetDirectoryName(path);
// Create the archive with the KML data
KmzFile kmz = KmzFile.Create(kml);
// Now find all the linked content in the KML so we can add the
// files to the KMZ archive
var links = new LinkResolver(kml);
// Next gather the local references and add them.
foreach (string relativePath in links.GetRelativePaths())
{
// Make sure it doesn't point to a directory below the base path
if (relativePath.StartsWith("..", StringComparison.Ordinal))
{
continue;
}
// Add it to the archive
string fullPath = Path.Combine(basePath, relativePath);
using (var file = File.OpenRead(fullPath))
{
kmz.AddFile(relativePath, file);
}
}
return kmz;
}
}
}