public static Open ( string file, XRefArchiveMode mode ) : |
||
file | string | |
mode | XRefArchiveMode | |
return |
public static XRefArchive Open(string file, XRefArchiveMode mode)
{
if (file == null)
{
throw new ArgumentNullException(nameof(file));
}
FileStream fs = null;
ZipArchive archive = null;
try
{
bool isReadOnly = false;
List<string> entries;
switch (mode)
{
case XRefArchiveMode.Read:
isReadOnly = true;
goto case XRefArchiveMode.Update;
case XRefArchiveMode.Update:
if (!File.Exists(file))
{
throw new FileNotFoundException($"File not found: {file}", file);
}
fs = File.Open(file, FileMode.Open, isReadOnly ? FileAccess.Read : FileAccess.ReadWrite);
archive = new ZipArchive(fs, isReadOnly ? ZipArchiveMode.Read : ZipArchiveMode.Update);
entries = (from entry in archive.Entries
select entry.FullName).ToList();
entries.Sort(StringComparer.OrdinalIgnoreCase);
break;
case XRefArchiveMode.Create:
var directory = Path.GetDirectoryName(file);
if (!string.IsNullOrEmpty(directory))
{
Directory.CreateDirectory(directory);
}
fs = File.Create(file);
archive = new ZipArchive(fs, ZipArchiveMode.Update);
entries = new List<string>();
break;
default:
throw new ArgumentOutOfRangeException(nameof(mode));
}
return new XRefArchive(mode, archive, entries);
}
catch (Exception) when (fs != null)
{
if (archive != null)
{
archive.Dispose();
}
fs.Close();
throw;
}
}
public async Task <bool> DownloadAsync(Uri uri, string outputFile) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } if (!uri.IsAbsoluteUri) { throw new ArgumentException("Relative path is not allowed.", nameof(uri)); } using (new LoggerPhaseScope(PhaseName)) using (new LoggerFileScope(outputFile)) { Logger.LogInfo($"Creating xref archive file..."); try { using (var xa = XRefArchive.Open(outputFile, XRefArchiveMode.Create)) { await DownloadCoreAsync(uri, xa, true); } } catch (Exception ex) { Logger.LogError($"Unable to create archive: {ex.Message}"); return(false); } Logger.LogInfo($"Xref archive file created."); return(true); } }