DotNetZip: Add Files to Dynamically Created Archive Directory - c#

I can't imagine this is hard to do, but I haven't been able to get it to work. I have a files class that just stores the location, directory, and name of the files I want to zip. The files I'm zipping exist on disk so the FileLocation is the full path. ZipFileDirectory doesn't exist on disk. If I have two items in my files list,
{ FileLocation = "path/file1.doc", ZipFileDirectory = #"\", FileName = "CustomName1.doc" },
{ FileLocation = "path/file2.doc", ZipFileDirectory = #"\NewDirectory", FileName = "CustomName2.doc" }
I would expect to see MyCustomName1.doc in the root, and a folder named NewDirectory containing MyCustomName2.doc, but what happens is they both end up in the root using this code:
using (var zip = new Ionic.Zip.ZipFile())
{
foreach (var file in files)
{
zip.AddFile(file.FileLocation, file.ZipFileDirectory).FileName = file.FileName;
}
zip.Save(HttpContext.Current.Response.OutputStream);
}
If I use this:
zip.AddFiles(files.Select(o => o.FileLocation), false, "NewDirectory");
Then it creates the new directory and puts all of the files inside, as expected, but then I lose the ability to use the custom naming with this method, and it also introduces more complexities that the first method would handle perfectly.
Is there a way I can get the first method (AddFile()) to work as I expect?

On further inspection, since posting a comment a few minutes ago, I suspect that setting FileName is erasing the archive path.
Testing confirms this.
Setting the name to #"NewDirectory\CustomName2.doc" will fix the problem.
You can also use #"\NewDirectory\CustomName2.doc"

Not sure if this exactly suites your needs but thought I would share. It is a method that is part of a helper class that I created to make working with DotNetZip a bit easier for my dev team. The IOHelper class is another simple helper class that you can ignore.
/// <summary>
/// Create a zip file adding all of the specified files.
/// The files are added at the specified directory path in the zip file.
/// </summary>
/// <remarks>
/// If the zip file exists then the file will be added to it.
/// If the file already exists in the zip file an exception will be thrown.
/// </remarks>
/// <param name="filePaths">A collection of paths to files to be added to the zip.</param>
/// <param name="zipFilePath">The fully-qualified path of the zip file to be created.</param>
/// <param name="directoryPathInZip">The directory within the zip file where the file will be placed.
/// Ex. specifying "files\\docs" will add the file(s) to the files\docs directory in the zip file.</param>
/// <param name="deleteExisting">Delete the zip file if it already exists.</param>
public void CreateZipFile(ICollection<FileInfo> filePaths, string zipFilePath, string directoryPathInZip, bool deleteExisting)
{
if (deleteExisting)
{
IOHelper ioHelper = new IOHelper();
ioHelper.DeleteFile(zipFilePath);
}
using (ZipFile zip = new ZipFile(zipFilePath))
{
foreach (FileInfo filePath in filePaths)
{
zip.AddFile(filePath.FullName, directoryPathInZip);
}
zip.Save();
}
}

Related

Accessing Images from resources.resx file not working with Image.FromFile method

I have an Image array, and I want to set an image in that array to be an image from Resources.resx file, I wrote this code here and gave me the exception that the image wasn't found.
string path = "PeanutToTheDungeon.Properties.Resources.ScaredMeter1"
imageArray[0] = Image.FromFile(path);
Does anyone know how to access local files using a path?
Also, the file does exist and it is named correctly too.
EmbeddedResources are not files, they are binary data encoded into the assembly itself. There are multiple ways to read them, the most common being to use the generated code from the resx (e.g., Resources.MyImageName).
The easiest way is just to do that. Find the .resx file in Visual Studio and look for the Resources.Designer.cs file. Inside that, you will find the generated property "ScaredMeter1", and it will likely be of type Bitmap (which derives from Image). To use it, you would have this code:
imageArray[0] = PeanutToTheDungeon.Properties.Resources.ScaredMeter1;
You can also create the image yourself like this:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Reflection;
internal static class EmbeddedResourceHelper
{
/// <summary>
/// Creates a new <see cref="System.Drawing.Image"/> by reading a <see cref="Stream"/> from an embedded resource.
/// </summary>
/// <param name="assembly">Assembly containing the embedded resource.</param>
/// <param name="resourceName">Name of the resource.</param>
/// <returns>The created <see cref="Image"/>.</returns>
/// <exception cref="ArgumentNullException">One of the arguments was <c>null</c>.</exception>
/// <exception cref="KeyNotFoundException">A resource named <paramref name="resourceName"/> was not found in <paramref name="assembly"/>.</exception>
public static Image ReadEmbeddedResourceImage(Assembly assembly, string resourceName)
{
if (assembly is null)
{
throw new ArgumentNullException(nameof(assembly));
}
if (resourceName is null)
{
throw new ArgumentNullException(nameof(resourceName));
}
using Stream stream = assembly.GetManifestResourceStream(resourceName)
?? throw new KeyNotFoundException($"{resourceName} is not a valid resource in {assembly.FullName}");
var image = Image.FromStream(stream);
return image;
}
}

How to create zip archive contains files with certain extensions only

I need to create zip archive which should contain files with certain extensions only, but I need to save the structure of the original directory.
For example, I have a directory with the following structure:
dir\
sub_dir1\
1.exe
sub_dir_2\
1.txt
1.exe
1.txt
1.bat
and I need to get an archive with the following structure (only .exe and .bat files):
dir\
sub_dir1\
1.exe
sub_dir_2\
1.exe
1.bat
I know how to find these files via Directory.GetFiles method:
var ext = new List<string> {".exe", ".bat"};
var myFiles = Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories)
.Where(s => ext.Any(e => s.EndsWith(e));
but I don't know how to save the archive's structure then.
How can I achieve such behavior?
You can get all the files with extension .exe and .bat from all the sub directories like:
IList<FileInfo> info = null;
DirectoryInfo dirInfo = new DirectoryInfo(path);
info = dirInfo
.GetFiles("*.*", SearchOption.AllDirectories)
.Where( f => f.Extension
.Equals(".exe", StringComparison.CurrentCultureIgnoreCase)
|| f.Extension
.Equals(".bat", StringComparison.CurrentCultureIgnoreCase)
)
.ToList()
;
Then based on this FileInfo list you can create you zip and folder structure.You can find the fileinfo details Here
System.IO.Directory.GetFiles("C:\\temp", "*.exe", SearchOption.AllDirectories); will return an array with the full file paths like:
[C:\temp\dir1\app1.exe]
[C:\temp\dir2\subdir1\app2.exe]
[C:\temp\dir3\subdir2\subdir3\app3.exe]
So you won't have any trouble to put these files in a zip container with ZipArchive.CreateEntry because this method will create the same directory structure in the zip. However, you should remove the C:\ at the beginning.
I believe this very nice tutorial will help you to do that.
If you want to keep empty folder in the target zip, maybe you have to use ZipArchive.CreateEntry method to do. In this demo, the author only use ZipArchive. CreateEntryFromFile method to archive a file from a file path.
Also you can use DotNetZip library for solving your problem. For example the following code snippet can help you. Use CreateZip() method. In brief you should find files for writing to archive GetFileNames() and create zip file using CreateZipFromFileNames():
/// <summary>
/// Create zip archive from root directory with search patterns
/// </summary>
/// <param name="rootDirectory">Root directory</param>
/// <param name="searchPatterns">Search patterns</param>
/// <param name="zipFileName">Zip archive file name</param>
public static void CreateZip(string rootDirectory, List<string> searchPatterns, string zipFileName)
{
var fileNames = GetFileNames(rootDirectory, searchPatterns, true);
CreateZipFromFileNames(rootDirectory, zipFileName, fileNames);
}
/// <summary>
/// Get file names filtered by search patterns
/// </summary>
/// <param name="rootDirectory">Root diirectory</param>
/// <param name="searchPatterns">Search patterns</param>
/// <param name="includeSubdirectories">True if it is included files from subdirectories</param>
/// <returns>List of file names</returns>
private static IEnumerable<string> GetFileNames(string rootDirectory, List<string> searchPatterns, bool includeSubdirectories)
{
var foundFiles = new List<string>();
var directoriesToSearch = new Queue<string>();
directoriesToSearch.Enqueue(rootDirectory);
// Breadth-First Search
while (directoriesToSearch.Count > 0)
{
var path = directoriesToSearch.Dequeue();
foreach (var searchPattern in searchPatterns)
{
foundFiles.AddRange(Directory.EnumerateFiles(path, searchPattern));
}
if (includeSubdirectories)
{
foreach (var subDirectory in Directory.EnumerateDirectories(path))
{
directoriesToSearch.Enqueue(subDirectory);
}
}
}
return foundFiles;
}
/// <summary>
/// Create zip archive from list of file names
/// </summary>
/// <param name="rootDirectroy">Root directory (for saving required structure of directories)</param>
/// <param name="zipFileName">File name of zip archive</param>
/// <param name="fileNames">List of file names</param>
private static void CreateZipFromFileNames(string rootDirectroy, string zipFileName, IEnumerable<string> fileNames)
{
var rootZipPath = Directory.GetParent(rootDirectroy).FullName;
using (var zip = new ZipFile(zipFileName))
{
foreach (var filePath in fileNames)
{
var directoryPathInArchive = Path.GetFullPath(Path.GetDirectoryName(filePath)).Substring(rootZipPath.Length);
zip.AddFile(filePath, directoryPathInArchive);
}
zip.Save();
}
}
Example of use:
CreateZip("dir", new List<string> { "*.exe", "*.bat" }, "myFiles.zip");
What #Didgeridoo said: DotNetZip. But DotNetZip lets you be even more expressive. For instance:
string cwd = Environment.CurrentDirectory ;
try
{
Environment.CurrentDirectory = #"c:\root\of\directory\tree\to\be\zipped" ;
using ( ZipFile zipfile = new ZipFile() )
{
zipfile.AddSelectedFiles( "name = *.bat OR name = *.exe" , true ) ;
zipfile.Save( #"c:\foo\bar\my-archive.zip") ;
}
}
finally
{
Environment.CurrentDirectory = cwd ;
}
Edited To Note: DotNetZip used to live at Codeplex. Codeplex has been shut down. The old archive is still available at Codeplex. It looks like the code has migrated to Github:
https://github.com/DinoChiesa/DotNetZip. Looks to be the original author's repo.
https://github.com/haf/DotNetZip.Semverd. This looks to be the currently maintained version. It's also packaged up an available via Nuget at https://www.nuget.org/packages/DotNetZip/

Copying files and subdirectories to another directory with existing files

I'm quite stuck on this problem for a while now. I need to copy (update) everything from Folder1\directory1 to Updated\directory1 overwriting same files but not deleting files that already exist on Updated\directory1 but does not exist on Folder1\directory1. To make my question clearer, this is my expected results:
C:\Folder1\directory1
subfolder1
subtext1.txt (2KB)
subfolder2
name.txt (2KB)
C:\Updated\directory1
subfolder1
subtext1.txt (1KB)
subtext2.txt (2KB)
Expected Result:
C:\Updated\directory1
subfolder1
subtext1.txt (2KB) <--- updated
subtext2.txt (2KB)
subfolder2 <--- added
name.txt (2KB) <--- added
I'm currently using Directory.Move(source, destination) but I'm having trouble about the destination part since some of it's destination folder is non-existent. My only idea is to use String.Trim to determine if there's additional folders but I can't really use it since the directories are supposed to be dynamic (there can be more subdirectories or more folders). I'm really stuck. Can you recommend some hints or some codes to get my stuff moving? Thanks!
I got this example from msdn http://msdn.microsoft.com/en-us/library/cc148994.aspx I think this is what you looking for
// To copy all the files in one directory to another directory.
// Get the files in the source folder. (To recursively iterate through
// all subfolders under the current directory, see
// "How to: Iterate Through a Directory Tree.")
// Note: Check for target path was performed previously
// in this code example.
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(s, destFile, true);
}
}
else
{
Console.WriteLine("Source path does not exist!");
}
If you need to deal with non existing folder path you should create a new folder
if (System.IO.Directory.Exists(targetPath){
System.IO.Directory.CreateDirectory(targetPath);
}
Parallel fast copying of all files from a folder to a folder with any level of nesting
Tested on copying 100,000 files
using System.IO;
using System.Linq;
namespace Utilities
{
public static class DirectoryUtilities
{
public static void Copy(string fromFolder, string toFolder, bool overwrite = false)
{
Directory
.EnumerateFiles(fromFolder, "*.*", SearchOption.AllDirectories)
.AsParallel()
.ForAll(from =>
{
var to = from.Replace(fromFolder, toFolder);
// Create directories if required
var toSubFolder = Path.GetDirectoryName(to);
if (!string.IsNullOrWhiteSpace(toSubFolder))
{
Directory.CreateDirectory(toSubFolder);
}
File.Copy(from, to, overwrite);
});
}
}
}
// This can be handled any way you want, I prefer constants
const string STABLE_FOLDER = #"C:\temp\stable\";
const string UPDATE_FOLDER = #"C:\temp\updated\";
// Get our files (recursive and any of them, based on the 2nd param of the Directory.GetFiles() method
string[] originalFiles = Directory.GetFiles(STABLE_FOLDER,"*", SearchOption.AllDirectories);
// Dealing with a string array, so let's use the actionable Array.ForEach() with a anonymous method
Array.ForEach(originalFiles, (originalFileLocation) =>
{
// Get the FileInfo for both of our files
FileInfo originalFile = new FileInfo(originalFileLocation);
FileInfo destFile = new FileInfo(originalFileLocation.Replace(STABLE_FOLDER, UPDATE_FOLDER));
// ^^ We can fill the FileInfo() constructor with files that don't exist...
// ... because we check it here
if (destFile.Exists)
{
// Logic for files that exist applied here; if the original is larger, replace the updated files...
if (originalFile.Length > destFile.Length)
{
originalFile.CopyTo(destFile.FullName, true);
}
}
else // ... otherwise create any missing directories and copy the folder over
{
Directory.CreateDirectory(destFile.DirectoryName); // Does nothing on directories that already exist
originalFile.CopyTo(destFile.FullName,false); // Copy but don't over-write
}
});
This was a quick one-off... no error handling was implemented here.
This will help you it is a generic recursive function so always merged subfolders as well.
/// <summary>
/// Directories the copy.
/// </summary>
/// <param name="sourceDirPath">The source dir path.</param>
/// <param name="destDirName">Name of the destination dir.</param>
/// <param name="isCopySubDirs">if set to <c>true</c> [is copy sub directories].</param>
/// <returns></returns>
public static void DirectoryCopy(string sourceDirPath, string destDirName, bool isCopySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo directoryInfo = new DirectoryInfo(sourceDirPath);
DirectoryInfo[] directories = directoryInfo.GetDirectories();
if (!directoryInfo.Exists)
{
throw new DirectoryNotFoundException("Source directory does not exist or could not be found: "
+ sourceDirPath);
}
DirectoryInfo parentDirectory = Directory.GetParent(directoryInfo.FullName);
destDirName = System.IO.Path.Combine(parentDirectory.FullName, destDirName);
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = directoryInfo.GetFiles();
foreach (FileInfo file in files)
{
string tempPath = System.IO.Path.Combine(destDirName, file.Name);
if (File.Exists(tempPath))
{
File.Delete(tempPath);
}
file.CopyTo(tempPath, false);
}
// If copying subdirectories, copy them and their contents to new location using recursive function.
if (isCopySubDirs)
{
foreach (DirectoryInfo item in directories)
{
string tempPath = System.IO.Path.Combine(destDirName, item.Name);
DirectoryCopy(item.FullName, tempPath, isCopySubDirs);
}
}
}

Is there a way to delete a folder the same way we delete a file automatically?

Using FileOptions.DeleteOnClose we can have a file delete itself when the last handle has been closed, this is very useful for temporary files that you want deleted when the program is closed. I created the following function
/// <summary>
/// Create a file in the temp directory that will be automatically deleted when the program is closed
/// </summary>
/// <param name="filename">The name of the file</param>
/// <param name="file">The data to write out to the file</param>
/// <returns>A file stream that must be kept in scope or the file will be deleted.</returns>
private static FileStream CreateAutoDeleteFile(string filename, byte[] file)
{
//get the GUID for this assembly.
var attribute = (GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), true)[0];
var assemblyGuid = attribute.Value;
//Create the folder for the files to be saved in.
string folder = Path.Combine(Path.GetTempPath(), assemblyGuid);
Directory.CreateDirectory(folder);
var fs = new FileStream(Path.Combine(folder, filename), FileMode.OpenOrCreate, FileAccess.ReadWrite,
FileShare.ReadWrite, 16 << 10, //16k buffer
FileOptions.DeleteOnClose);
//Check and see if the file has already been created, if not write it out.
if (fs.Length == 0)
{
fs.Write(file, 0, file.Length);
fs.Flush();
}
return fs;
}
Everything works perfectly but I leave a leftover folder in the users %TEMP% folder. I would like to be a good citizen and also delete the folder when I am done but I don't think there is a way to do that like I do with files.
Is there a way to auto-delete the folder like I delete the file, or am I just going to have to live with the folder remaining or having to explicitly call Directory.Delete when my program closes.

how to get file from resources as a stream? (.net)

I've got few files in resources (xsd files) that i use for validating received xml messages. The resource file i use is named AppResources.resx and it contains a file called clientModels.xsd. When i try to use the file like this: AppResources.clientModels, i get a string with the file's content. i would like to get a stream instead.
i do not wish to use assembly.GetManifestResourceStream as i had bad experiences with it (using these streams to archive files with SharpZipLib didn't work for some reason).
is there any other way to do it? i've heard about ResourceManager - is it anything that could help me?
Could you feed the string you get into a System.IO.StringReader, perhaps? That may do what you want. You may also want to check out MemoryStream.
here is the code from the link
//Namespace reference
using System;
using System.Resources;
#region ReadResourceFile
/// <summary>
/// method for reading a value from a resource file
/// (.resx file)
/// </summary>
/// <param name="file">file to read from</param>
/// <param name="key">key to get the value for</param>
/// <returns>a string value</returns>
public string ReadResourceValue(string file, string key)
{
//value for our return value
string resourceValue = string.Empty;
try
{
// specify your resource file name
string resourceFile = file;
// get the path of your file
string filePath = System.AppDomain.CurrentDomain.BaseDirectory.ToString();
// create a resource manager for reading from
//the resx file
ResourceManager resourceManager = ResourceManager.CreateFileBasedResourceManager(resourceFile, filePath, null);
// retrieve the value of the specified key
resourceValue = resourceManager.GetString(key);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
resourceValue = string.Empty;
}
return resourceValue;
}
#endregion
I did not write the code it came from
http://www.dreamincode.net/code/snippet1683.htm
HTH
bones
I have a zip file loaded as a resource, and referencing it directly from the namespace gives me bytes, not a string. Right-click on your file in the resources designer, and change the filetype from text to binary. Then you will get a bytearray, which you could load into a MemoryStream.

Categories

Resources