C# Get top level files from zip file only - c#

I am trying to get all the file names that are located in the top level of a zip file and not anything in subdirectories.
The code I'm currently using is
using System.IO.Compression.ZipFile;
using (var zip = ZipFile.OpenRead(pathToZip))
{
foreach (var e in zip.Entries)
{
var filename = e.Name;
}
}
But this code gets all the files in the zip. Any help is much apricated.
Thanks

This code will extract only files that are not contained in a directory:
using (var zip = ZipFile.OpenRead(pathToZip))
{
foreach (var e in zip.Entries.Where(e => !e.FullName.Contains("/")))
{
{
var filename = e.Name;
Console.WriteLine(filename);
}
}
}

Related

C# returning all files located in a directory which has folders in it [duplicate]

This question already has answers here:
How to recursively list all the files in a directory in C#?
(23 answers)
Closed 2 years ago.
How can I retrieve all the files in a directory that has files, sub-folders, and files in that folders.
NOTE: The folder/files is not constant
You can use the DirectoryInfo.GetFiles method with the RecurseSubdirectories option.
using System.IO;
FileInfo[] files
= new DirectoryInfo(#"C:\Program Files")
.GetFiles("*", new EnumerationOptions { RecurseSubdirectories = true });
If you don't need the full list of files, it may be faster to enumerate the directory's contents.
using System.IO;
using System.Collections.Generic;
using System.Linq;
var directory = new DirectoryInfo(#"C:\Program Files");
IEnumerable<FileInfo> files
= from file in directory.EnumerateFiles("*", new EnumerationOptions { RecurseSubdirectories = true })
where file.Name = "target.txt"
select file;
foreach (FileInfo file in files)
{
//...
}
You can use Directory.GetFiles(path) and Directory.GetDirectories(path)
static void ScanDir(string path, int spaces = 0)
{
var files = Directory.GetFiles(path);
foreach (var file in files)
{
for (int i = 0; i < spaces; i++)
Console.Write(" "); // Just for styling
Console.WriteLine(file);
}
var dirs = Directory.GetDirectories(path);
foreach (var dir in dirs)
{
ScanDir(dir, spaces + 4);
}
}
static void Main()
{
ScanDir("C:\\path\\to");
}

How to compress both files and folders with ZipFile API

I want to compress Zip to be same structure with folder.
but, ZipFile API seems unable to compress folder.
How to compress these folder structure?
The following code can't compress folder itself.
using (ZipArchive archive = ZipFile.Open(Path.Combine(m_strWorkingDirectory, "build.zip"), ZipArchiveMode.Create))
{
foreach( string path in m_listTargetPath )
{
string strPath = Path.Combine(m_strWorkingDirectory, path);
archive.CreateEntryFromFile(strPath, path);
}
}
If ZipFile.CreateFromDirectory() doesn't do what you need (I thought it would) then you can just get all the files/folders you need and add them in using an extension method:
public static class FileExtensions
{
public static IEnumerable<FileSystemInfo> AllFilesAndFolders(this DirectoryInfo dir)
{
foreach (var f in dir.GetFiles())
{
yield return f;
}
foreach (var d in dir.GetDirectories())
{
yield return d;
foreach (var o in AllFilesAndFolders(d))
{
yield return o;
}
}
}
}
And then using your same format, you should be able to do something like so (not tested):
DirectoryInfo dir = new DirectoryInfo(m_strWorkingDirectory);
using (ZipArchive archive = ZipFile.Open(Path.Combine(m_strWorkingDirectory, "build.zip"), ZipArchiveMode.Create))
{
foreach (FileInfo file in dir.AllFilesAndFolders().Where(o => o is FileInfo).Cast<FileInfo>())
{
var relPath = file.FullName.Substring(dir.FullName.Length + 1);
archive.CreateEntryFromFile(file.FullName, relPath);
}
}

Move files directories and sub directories to another directory Conditionally (Move only Last 5 days created files and directories) in C#

My Source directory "D:\Source"
Destination "D:\Destination"
source directory contains some files and folders with different creation dates,
i want to move all files and folders whose creation date less than last 5 days
for example today is 28/11/2015 and i want to Move all files and folders from source before creating 23/11/205.
i'm searching since 2 days but no success.
here is my Attempt
var sourcePath = "D:\\Source";
var destinationPath = "D:\\Destination";
var dInfo = new DirectoryInfo(sourcePath)
var files = (from filew in dInfo.EnumerateFiles(sourcePath)
orderby filew.CreationTime.Date < DateTime.Now.Date.AddDays(-5) ascending
select filew.Name).Distinct();
var directories = (from filew in dInfo.EnumerateDirectories(sourcePath)
orderby filew.CreationTime.Date < DateTime.Now.Date.AddDays(-5) ascending
select filew.Name).Distinct();
foreach (var dir in directories)
{
var dest = Path.Combine(destinationPath, Path.GetFileName(dir));
Directory.Move(dir, dest);
}
foreach (var file in files)
{
var dest = Path.Combine(destinationPath, Path.GetFileName(file));
File.Move(file, dest);
}
ERROR : Second path fragment must not be a drive or UNC name.
please help me
You have to call EnumerateFiles and EnumerateDirectories without parameters:
dInfo.EnumerateFiles()
dInfo.EnumerateDirectories()
The information about sourcePath is already in the dInfo object. The parameter would be used to apply a filter.
UPDATE:
And the EnumerateFiles() function just returns the file names without pathes. So you should use something like that:
foreach (var file in files)
{
var src = Path.Combine(sourcePath, file);
var dest = Path.Combine(destinationPath, file);
File.Move(src, dest);
}
You would need to do it recursively as there can be sub directories within the directory, where the same rule would apply. Refer to code below.
public static void MoveFilesAndFolders(string sourcePath, string destinationPath)
{
var directories = Directory.GetDirectories(sourcePath);
foreach (var directory in directories)
{
var subDirectory = new DirectoryInfo(directory);
//Create sub directory in the destination folder if the business rules is satisfied
if (DateTime.Today.Subtract(File.GetCreationTime(directory)).Days < 5)
{
var newDestinationDirectory = Directory.CreateDirectory(Path.Combine(destinationPath, subDirectory.Name));
MoveFilesAndFolders(subDirectory.FullName, newDestinationDirectory.FullName);
}
}
foreach (var file in Directory.GetFiles(sourcePath))
{
var fileName = Path.GetFileName(file);
//Copy the file to destination folder if the business rule is satisfied
if (!string.IsNullOrEmpty(fileName))
{
var newFilePath = Path.Combine(destinationPath, fileName);
if (!File.Exists(newFilePath) && (DateTime.Today.Subtract(File.GetCreationTime(file)).Days < 5)))
{
File.Move(file, newFilePath);
}
}
}
}

FIND A SPECIFIC FILE IN A FOLDER "C:\TEST" THAT CONTAINS MULTIPLE ARCHIVES ".ZIP" USING C#

I have a folder "c:\test" which contains multiple archives. How do I search through all the archives in this folder for a specific file.
This only search a particular archive using ZipPath:
private void button1_Click(object sender, EventArgs e)
{
string zipPath = #"C:\Test\archive1.zip";
string filetosearch = "testfile";
using (ZipArchive archive = ZipFile.OpenRead(zipPath))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
var position = entry.Name.IndexOf(filetosearch , StringComparison.InvariantCultureIgnoreCase);
if (position > -1)
{
listView1.Items.Add(entry.Name);
}
}
}
}
Is it possible to search all the archives in this folder i.e archive1 to archive70
You can use the following code:
foreach(var zipPath in Directory.GetFiles("C:\\Test"))
{
using (ZipArchive archive = ZipFile.OpenRead(zipPath))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
var position = entry.Name.IndexOf(filetosearch , StringComparison.InvariantCultureIgnoreCase);
if (position > -1)
{
listView1.Items.Add(entry.Name);
}
}
}
}
The code gets all the files in the directory and iterates through them. If you need to filter the files by extension you can check it inside the foreach loop.
You probably want something along the lines of
string[] filePaths = Directory.GetFiles(#"c:\Test\", "*.zip")
Then change you click code to
foreach(var filePath in filePaths){
//your code here for each path
}
You may use following code
string[] filePaths = Directory.GetFiles(#"c:\test", "*.zip");
string filetosearch = "testfile";
foreach (var item in filePaths)
{
string name = Path.GetFileName(item);
if (name.IndexOf(filetosearch, StringComparison.InvariantCultureIgnoreCase) != -1)
{
//item is path of that file
}
}

Unzip one File from Directory

Everything is working fine.. I can Unzip files, from an Zip/Rar .. Archive.
The Problem is, how to Unzip a file, thats in a Directory?
To Unzip a File directly I use (SharpZipLib):
FastZip fastZip = new FastZip();
fastZip.ExtractZip(source, targetDirectory, null);
using (var fs = new FileStream(source, FileMode.Open, FileAccess.Read))
using (var zf = new ZipFile(fs))
{
var ze = zf.GetEntry("toc.out");
if (ze == null)
{
throw new ArgumentException("toc.out", "not found in Zip");
}
using (var s = zf.GetInputStream(ze))
{
// do something with ZipInputStream
}
}
}
Or with DotNetZip/ZipDotNet:
using (ZipFile zip = ZipFile.Read(source))
{
ZipEntry e = zip["toc.out"];
e.Extract();
}
Thats not working, cause hes searching the file in the root..
And I also wont do something like: DirectoryName/toc.out
How can I achieve this`? Isn't there a parameter, where I can include all subfolders - for searching or something similar? :(
You can write a LINQ expression to find the file in sub folders as shown below
DirectoryInfo dirInfo = new DirectoryInfo(#"C:\");
foreach (var file in dirs.Select(dir => dir.EnumerateFiles().Where(i => i.Name.ToLower() == "wsdl.zip").FirstOrDefault()).Where(file => file != null))
{
Console.WriteLine(file.ToString());
Console.WriteLine(file.Length);
}
The above code searches all subfolder under C drive for the file wsdl.zip and prints its name and length to the console.
Hope that helps.
You can check the last part of the Name of the entry. Even if the file is in a subfolder, the Name entry would be something like "Folder/file.ext".
An extension method to accomplish this would be like:
public static ZipEntry GetEntryExt(this ZipFile file, string fileName)
{
foreach (ZipEntry entry in file)
{
if (entry.IsFile && entry.Name.EndsWith(Path.DirectorySeparatorChar + fileName))
return entry;
}
return null;
}

Categories

Resources