Skip to content

Instantly share code, notes, and snippets.

@stdray
Last active September 11, 2015 12:41
Show Gist options
  • Select an option

  • Save stdray/02d95ed49dba13b62d17 to your computer and use it in GitHub Desktop.

Select an option

Save stdray/02d95ed49dba13b62d17 to your computer and use it in GitHub Desktop.
public static class ZipHelper
{
const string ZipExt = ".zip";
public class FileContent : IDisposable
{
public readonly string FileName;
public readonly string NameInArchive;
public readonly Stream Content;
public FileContent(string fileName, Stream content, string nameInArchive)
{
FileName = fileName;
NameInArchive = nameInArchive;
Content = content;
}
public bool IsInArchive { get { return NameInArchive != null; } }
public string Name { get { return NameInArchive ?? FileName; } }
public string Extension { get { return Path.GetExtension(Name); } }
public void Dispose()
{
Content.Dispose();
}
}
public static IEnumerable<FileContent> GetContents(string fileName, Stream stream)
{
var ext = Path.GetExtension(fileName).ToLowerInvariant();
if (ext == ZipExt)
using (var zip = new ZipArchive(stream))
foreach (var entry in zip.Entries)
yield return new FileContent(fileName, entry.Open(), entry.Name);
else
yield return new FileContent(fileName, stream, null);
}
}
public override ExternalLoaderResult<FileItem> ProccessFile(FileItem item, Stream stream)
{
var result = new ExternalLoaderResult<FileItem>(item);
foreach (var content in ZipHelper.GetContents(item.Path, stream))
if (content.Extension == XmlExt)
try
{
TransformXml(result, content.Content, content.Name);
}
catch (Exception ex)
{
result.AddError("Error in " + content.Name, ex);
}
finally
{
content.Dispose();
}
return result;
}
public IEnumerable<TExternal> GetExternalDocuments()
{
foreach (var fileItem in FileEnumerator.Enumerate())
foreach (var content in ZipHelper.GetContents(fileItem.Path, FileEnumerator.GetFile(fileItem.Path)))
using (content)
yield return Deserialize(content.Content);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment