protected override Task <IActionResult> CreateDirectoryGetResponse(DirectoryInfoBase info, string localFilePath) { if (!Request.Query.TryGetValue("fileName", out var fileName)) { fileName = Path.GetFileName(Path.GetDirectoryName(localFilePath)) + ".zip"; } var result = new FileCallbackResult("application/zip", (outputStream, _) => { // Note that a stream wrapper is no longer needed for ZipArchive, this was fixed in its implementation. using (var zip = new ZipArchive(outputStream, ZipArchiveMode.Create, leaveOpen: false)) { foreach (FileSystemInfoBase fileSysInfo in info.GetFileSystemInfos()) { var directoryInfo = fileSysInfo as DirectoryInfoBase; if (directoryInfo != null) { zip.AddDirectory(directoryInfo, Tracer, fileSysInfo.Name); } else { // Add it at the root of the zip zip.AddFile(fileSysInfo.FullName, Tracer, String.Empty); } } } return(Task.CompletedTask); }) { FileDownloadName = fileName }; return(Task.FromResult((IActionResult)result)); }
static FileSystemInfoBase GetSourceFileInfo(IFileSystem srcFileSystem, string srcFile) { if (srcFile.EndsWith("\\")) { return(srcFileSystem.DirectoryInfo.FromDirectoryName(srcFile)); } var srcParent = srcFile.Substring(0, srcFile.LastIndexOf('\\') + 1); if (srcParent.Length < "x:\\".Length) { throw new ArgumentException("Invalid destination!"); } else if (srcParent.Equals("x:\\", StringComparison.OrdinalIgnoreCase)) { return(srcFileSystem.DirectoryInfo.FromDirectoryName(srcFile)); } string name = srcFile.Substring(srcFile.LastIndexOf('\\') + 1); DirectoryInfoBase parent = srcFileSystem.DirectoryInfo.FromDirectoryName(srcParent); FileSystemInfoBase match = parent.GetFileSystemInfos().Where(f => f.Name == name).FirstOrDefault(); if (match == null) { throw new FileNotFoundException(srcFile + " does not exists"); } return(match); }
protected override Task <HttpResponseMessage> CreateDirectoryGetResponse(DirectoryInfoBase info, string localFilePath) { HttpResponseMessage response = Request.CreateResponse(); // GetQueryNameValuePairs returns an IEnumerable<KeyValuePair<string, string>> // KeyValuePair is a value type. var fileName = Request.GetQueryNameValuePairs().FirstOrDefault(p => p.Key.Equals("fileName", StringComparison.OrdinalIgnoreCase)).Value; fileName = fileName ?? Path.GetFileName(Path.GetDirectoryName(localFilePath)) + ".zip"; response.Content = ZipStreamContent.Create(fileName, Tracer, zip => { foreach (FileSystemInfoBase fileSysInfo in info.GetFileSystemInfos()) { var directoryInfo = fileSysInfo as DirectoryInfoBase; if (directoryInfo != null) { zip.AddDirectory(directoryInfo, Tracer, fileSysInfo.Name); } else { // Add it at the root of the zip zip.AddFile(fileSysInfo.FullName, Tracer, String.Empty); } } }); return(Task.FromResult(response)); }
private static void InternalAddDirectory(ZipArchive zipArchive, DirectoryInfoBase directory, ITracer tracer, string directoryNameInArchive, IList <ZipArchiveEntry> files = null) { bool any = false; foreach (var info in directory.GetFileSystemInfos()) { any = true; var subDirectoryInfo = info as DirectoryInfoBase; if (subDirectoryInfo != null) { string childName = ForwardSlashCombine(directoryNameInArchive, subDirectoryInfo.Name); InternalAddDirectory(zipArchive, subDirectoryInfo, tracer, childName, files); } else { var entry = zipArchive.AddFile((FileInfoBase)info, tracer, directoryNameInArchive); files?.Add(entry); } } if (!any) { // If the directory did not have any files or folders, add a entry for it zipArchive.CreateEntry(EnsureTrailingSlash(directoryNameInArchive)); } }
/// <summary> /// Extracts a snippet. /// </summary> /// <param name="fileSystemInfo">The file system info.</param> /// <param name="pattern">The extraction pattern.</param> /// <returns>The extracted snippet.</returns> public Snippet Extract(FileSystemInfoBase fileSystemInfo, string pattern) { // Get the directory DirectoryInfoBase directoryInfo = this.ConvertToDirectory(fileSystemInfo); // Use * as pattern when none is set if (string.IsNullOrWhiteSpace(pattern)) { pattern = "*"; } try { // Search file system info from pattern FileSystemInfoBase[] fileSystemInfoBase = pattern .Split(new char[] { '|', ';' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => x.Trim()) .Where(x => !string.IsNullOrWhiteSpace(x)) .SelectMany(x => directoryInfo.GetFileSystemInfos(x, SearchOption.AllDirectories)) .OrderByDescending(x => x is DirectoryInfoBase) .ThenBy(x => x.FullName) .ToArray(); // Build snippet return(this.BuildSnippet(directoryInfo, fileSystemInfoBase)); } // Rethrow a snippet extraction exception if the directory is not found catch (DirectoryNotFoundException) { throw new SnippetExtractionException("Cannot find directory", pattern); } }
public void Reset() { Dispose(true, true); // Safely get the enumerators, including in the case where the root is not accessable if (root != null) { try { fileEnumerator = root.GetFileSystemInfos(pattern, SearchOption.TopDirectoryOnly).AsEnumerable <FileSystemInfoBase>().GetEnumerator(); } catch (Exception ex) { errors.Add(ex); fileEnumerator = null; } try { directoryEnumerator = root.GetDirectories("*", SearchOption.TopDirectoryOnly).AsEnumerable <DirectoryInfoBase>().GetEnumerator(); } catch (Exception ex) { errors.Add(ex); directoryEnumerator = null; } } }
public static void AddDirectory(this ZipArchive zipArchive, DirectoryInfoBase directory, ITracer tracer, string directoryNameInArchive) { bool any = false; foreach (var info in directory.GetFileSystemInfos()) { any = true; var subDirectoryInfo = info as DirectoryInfoBase; if (subDirectoryInfo != null) { string childName = ForwardSlashCombine(directoryNameInArchive, subDirectoryInfo.Name); zipArchive.AddDirectory(subDirectoryInfo, tracer, childName); } else { zipArchive.AddFile((FileInfoBase)info, tracer, directoryNameInArchive); } } if (!any) { // If the directory did not have any files or folders, add a entry for it zipArchive.CreateEntry(EnsureTrailingSlash(directoryNameInArchive)); } }
protected override Task <HttpResponseMessage> CreateDirectoryGetResponse(DirectoryInfoBase info, string localFilePath) { HttpResponseMessage response = Request.CreateResponse(); var ms = new MemoryStream(); using (var zip = new ZipArchive(ms, ZipArchiveMode.Create, leaveOpen: true)) { foreach (FileSystemInfoBase fileSysInfo in info.GetFileSystemInfos()) { var directoryInfo = fileSysInfo as DirectoryInfoBase; if (directoryInfo != null) { zip.AddDirectory(directoryInfo, fileSysInfo.Name); } else { // Add it at the root of the zip zip.AddFile(fileSysInfo.FullName, String.Empty); } } } ms.Seek(0, SeekOrigin.Begin); response.Content = new StreamContent(ms); response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip"); response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); // Name the zip after the folder. e.g. "c:\foo\bar\" --> "bar" response.Content.Headers.ContentDisposition.FileName = Path.GetFileName(Path.GetDirectoryName(localFilePath)) + ".zip"; return(Task.FromResult(response)); }
static int Main(string[] args) { try { var arg = new CommandArguments(args); var fileSystem = arg.FileSystem; string cd = fileSystem.Directory.GetCurrentDirectory(); string path = Path.Combine(cd, arg.Path); var info = new FileInfo(path); DirectoryInfoBase parent = fileSystem.DirectoryInfo.FromDirectoryName(info.Directory.FullName); FileSystemInfoBase file = parent.GetFileSystemInfos().Where(f => f.Name == info.Name).FirstOrDefault(); if (file == null) { throw new FileNotFoundException(info.FullName + " does not exists."); } else if (file is DirectoryInfoBase) { throw new NotSupportedException("Delete directory is not supported."); } file.Delete(); return(0); } catch (Exception ex) { Console.WriteLine(ex); return(-1); } }
static void ListDirectory(DirectoryInfoBase dir) { FileSystemInfoBase[] children = dir.GetFileSystemInfos(); Console.WriteLine(); Console.WriteLine(" Directory of {0}", dir.FullName.TrimEnd('\\')); Console.WriteLine(); foreach (DirectoryInfoBase info in children.Where(d => d is DirectoryInfoBase)) { Console.WriteLine(String.Format("{0} <DIR> {1}", ToDisplayString(info.LastWriteTime), info.Name)); } int count = 0; long total = 0; foreach (FileInfoBase info in children.Where(d => !(d is DirectoryInfoBase))) { FileInfoBase file = (FileInfoBase)info; Console.WriteLine(String.Format("{0} {1,17} {2}", ToDisplayString(info.LastWriteTime), file.Length.ToString("#,##0"), info.Name)); total += file.Length; ++count; } Console.WriteLine(String.Format("{0,16} File(s) {1,14} bytes", count.ToString("#,##0"), total.ToString("#,##0"))); }
private IEnumerable <FileSystemInfoBase> GetFilteredItems(DirectoryInfoBase directory) { var breakSearch = false; foreach (var item in directory.GetFileSystemInfos()) { if (Status == FileSystemVisitorStatus.Stopped) { break; } var excludeItem = false; var dir = item as DirectoryInfoBase; if (dir != null) { DirectoryFoundEvent?.Invoke(dir, ref breakSearch, ref excludeItem); if (!breakSearch && !excludeItem) { foreach (var i in GetFilteredItems(dir)) //going recursion here { yield return(i); } } } else { var file = item as FileInfoBase; if (file != null) { FileFoundEvent?.Invoke(file, ref breakSearch, ref excludeItem); } } if (breakSearch) { Status = FileSystemVisitorStatus.Stopped; } if (excludeItem) { continue; } if (Filter != null && !Filter.Invoke(item)) { continue; } FilterItemActions(item, ref breakSearch, ref excludeItem); if (!excludeItem) { yield return(item); } else if (breakSearch) { Status = FileSystemVisitorStatus.Stopped; } } }
public static bool IsEmpty(this DirectoryInfoBase info) { if (info == null) { return(true); } FileSystemInfoBase[] fileSystemInfos = OperationManager.Attempt(() => info.GetFileSystemInfos()); return(fileSystemInfos.Length == 0); }
public IEnumerable <FileSystemInfoBase> GetDirectoryInnerEntities(DirectoryInfoBase entryDirectoryInfo) { bool isCancelled = false; foreach (var entryDirectoryEntity in entryDirectoryInfo.GetFileSystemInfos()) { if (isCancelled) { break; } EntityFoundArgs entityFoundArgs = new EntityFoundArgs() { EntityInfo = entryDirectoryEntity }; if (entryDirectoryEntity is DirectoryInfoBase) { entityFoundArgs.Message = "Directory found"; OnDirectoryFound(entityFoundArgs); if ((IsFilterAlgorithmPassed == null || IsFilterAlgorithmPassed(entryDirectoryEntity)) && !entityFoundArgs.IsExcluded) { entityFoundArgs.Message = "Filtered directory found"; OnFilteredDirectoryFound(entityFoundArgs); yield return(entryDirectoryEntity); } } else { entityFoundArgs.Message = "File found"; OnFileFound(entityFoundArgs); if ((IsFilterAlgorithmPassed == null || IsFilterAlgorithmPassed(entryDirectoryEntity)) && !entityFoundArgs.IsExcluded) { entityFoundArgs.Message = "Filtered file found"; OnFilteredFileFound(entityFoundArgs); yield return(entryDirectoryEntity); } } if (entityFoundArgs.IsCancelled) { isCancelled = true; } } if (!isCancelled) { foreach (var entryDirectoryEntity in entryDirectoryInfo.GetDirectories()) { foreach (var entity in GetDirectoryInnerEntities(entryDirectoryEntity)) { yield return(entity); } } } }
protected virtual Task <IActionResult> CreateDirectoryGetResponse(DirectoryInfoBase info, string localFilePath) { Contract.Assert(info != null); try { // Enumerate directory IEnumerable <VfsStatEntry> directory = GetDirectoryResponse(info.GetFileSystemInfos()); return(Task.FromResult((IActionResult)Ok(directory))); } catch (Exception e) { Tracer.TraceError(e); return(Task.FromResult((IActionResult)StatusCode(StatusCodes.Status500InternalServerError, e.Message))); } }
private static void DeleteDirectoryContentsSafe(DirectoryInfoBase directoryInfo) { try { if (directoryInfo.Exists) { foreach (var fsi in directoryInfo.GetFileSystemInfos()) { DeleteFileSystemInfo(fsi); } } } catch { } }
private static void DeleteDirectoryContentsSafe(DirectoryInfoBase directoryInfo, bool ignoreErrors) { try { if (directoryInfo.Exists) { foreach (var fsi in directoryInfo.GetFileSystemInfos()) { DeleteFileSystemInfo(fsi, ignoreErrors); } } } catch when(ignoreErrors) { } }
protected virtual Task <HttpResponseMessage> CreateDirectoryGetResponse(DirectoryInfoBase info, string localFilePath) { Contract.Assert(info != null); try { // Enumerate directory IEnumerable <VfsStatEntry> directory = GetDirectoryResponse(info.GetFileSystemInfos()); HttpResponseMessage successDirectoryResponse = Request.CreateResponse <IEnumerable <VfsStatEntry> >(HttpStatusCode.OK, directory); return(Task.FromResult(successDirectoryResponse)); } catch (Exception e) { Tracer.TraceError(e); HttpResponseMessage errorResponse = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message); return(Task.FromResult(errorResponse)); } }
static void CopyInternal(IFileSystem srcFileSystem, DirectoryInfoBase srcFileInfo, IFileSystem dstFileSystem, DirectoryInfoBase dstFileInfo) { foreach (FileSystemInfoBase src in srcFileInfo.GetFileSystemInfos()) { if (src is FileInfoBase) { var dst = dstFileSystem.FileInfo.FromFileName(Path.Combine(dstFileInfo.FullName, src.Name)); _semaphore.WaitOne(); _tasks.Add(CopyInternalAsync(srcFileSystem, (FileInfoBase)src, dstFileSystem, (FileInfoBase)dst).Finally(() => _semaphore.Release())); } else { // recursive var dst = dstFileSystem.DirectoryInfo.FromDirectoryName(Path.Combine(dstFileInfo.FullName, src.Name)); CopyInternal(srcFileSystem, (DirectoryInfoBase)src, dstFileSystem, (DirectoryInfoBase)dst); } } }
protected virtual Task <HttpResponseMessage> CreateDirectoryGetResponse(HttpRequest request, DirectoryInfoBase info, string localFilePath) { ArgumentNullException.ThrowIfNull(info); try { // Enumerate directory var directory = GetDirectoryResponse(request, info.GetFileSystemInfos()); var successDirectoryResponse = CreateResponse(HttpStatusCode.OK, directory); return(Task.FromResult(successDirectoryResponse)); } catch (Exception e) { _logger.LogError(e, e.Message); HttpResponseMessage errorResponse = CreateResponse(HttpStatusCode.InternalServerError, e.Message); return(Task.FromResult(errorResponse)); } }
protected virtual Task <HttpResponseMessage> CreateDirectoryGetResponse(HttpRequest request, DirectoryInfoBase info, string localFilePath) { if (info == null) { throw new ArgumentNullException(nameof(info)); } try { // Enumerate directory var directory = GetDirectoryResponse(request, info.GetFileSystemInfos()); var successDirectoryResponse = CreateResponse(HttpStatusCode.OK, directory); return(Task.FromResult(successDirectoryResponse)); } catch (Exception e) { // TODO: log HttpResponseMessage errorResponse = CreateResponse(HttpStatusCode.InternalServerError, e.Message); return(Task.FromResult(errorResponse)); } }
private IEnumerable <VfsStatEntry> GetDirectoryResponse(DirectoryInfoBase info) { Contract.Assert(info != null); string baseAddress = Request.RequestUri.AbsoluteUri; foreach (FileSystemInfoBase fileSysInfo in info.GetFileSystemInfos()) { bool isDirectory = (fileSysInfo.Attributes & FileAttributes.Directory) != 0; string mime = isDirectory ? _directoryMediaType.ToString() : MediaTypeMap.GetMediaType(fileSysInfo.Extension).ToString(); string unescapedHref = isDirectory ? fileSysInfo.Name + UriSegmentSeparator : fileSysInfo.Name; long size = isDirectory ? 0 : ((FileInfoBase)fileSysInfo).Length; yield return(new VfsStatEntry { Name = fileSysInfo.Name, MTime = fileSysInfo.LastWriteTimeUtc, Mime = mime, Size = size, Href = baseAddress + Uri.EscapeUriString(unescapedHref), }); } }
protected override Task <HttpResponseMessage> CreateDirectoryGetResponse(DirectoryInfoBase info, string localFilePath) { HttpResponseMessage response = Request.CreateResponse(); response.Content = ZipStreamContent.Create(Path.GetFileName(Path.GetDirectoryName(localFilePath)) + ".zip", Tracer, zip => { foreach (FileSystemInfoBase fileSysInfo in info.GetFileSystemInfos()) { var directoryInfo = fileSysInfo as DirectoryInfoBase; if (directoryInfo != null) { zip.AddDirectory(directoryInfo, fileSysInfo.Name); } else { // Add it at the root of the zip zip.AddFile(fileSysInfo.FullName, String.Empty); } } }); return(Task.FromResult(response)); }
static FileSystemInfoBase GetDestinationFileInfo(IFileSystem dstFileSystem, string dstFile, FileSystemInfoBase srcFileInfo) { if (dstFile.EndsWith("\\")) { if (srcFileInfo is FileInfoBase) { dstFile = Path.Combine(dstFile, srcFileInfo.Name); return(dstFileSystem.FileInfo.FromFileName(dstFile)); } else { return(dstFileSystem.DirectoryInfo.FromDirectoryName(dstFile)); } } var dstFileInfo = new FileInfo(dstFile); var dstParent = dstFileInfo.Directory; if (dstParent.FullName.Length < "x:\\".Length) { throw new ArgumentException("Invalid destination!"); } else if (dstParent.FullName.Equals("x:\\", StringComparison.OrdinalIgnoreCase)) { if (srcFileInfo is FileInfoBase) { dstFile = Path.Combine(dstFile, srcFileInfo.Name); return(dstFileSystem.FileInfo.FromFileName(dstFile)); } else { return(dstFileSystem.DirectoryInfo.FromDirectoryName(dstFile)); } } DirectoryInfoBase parent = dstFileSystem.DirectoryInfo.FromDirectoryName(dstParent.FullName); FileSystemInfoBase match = parent.GetFileSystemInfos().Where(f => f.Name == dstFileInfo.Name).FirstOrDefault(); if (match is DirectoryInfoBase) { if (srcFileInfo is DirectoryInfoBase) { return(match); } else { return(dstFileSystem.FileInfo.FromFileName(Path.Combine(match.FullName, srcFileInfo.Name))); } } else if (match is FileInfoBase) { if (srcFileInfo is DirectoryInfoBase) { throw new InvalidOperationException("Cannot xcopy dir to file."); } else { return(match); } } else { if (srcFileInfo is DirectoryInfoBase) { throw new DirectoryNotFoundException(dstFileInfo.FullName + " does not exist."); } else { return(dstFileSystem.FileInfo.FromFileName(dstFile)); } } }