How to upload a file to S3 using SSIS? - c#

This was my question a few hours ago and just trying to save someone all the effort i had to go through to figure this out.
Basic code on how to upload file to S3 using script task in SSIS. Be sure to add Amazon.S3.dll and Amazon.Core.dll to your references.
using Amazon.S3;
using Amazon.S3.Transfer;
using Amazon.S3.Model;
using System.IO;
namespace tests
{
class Program
{
static ScriptMain()
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}
static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
string path = #"Path to DLLs";
if (args.Name.Contains("AWSSDK.Core"))
{
return System.Reflection.Assembly.LoadFile(System.IO.Path.Combine(path, "AWSSDK.Core.dll"));
}
if (args.Name.Contains("AWSSDK.S3"))
{
return System.Reflection.Assembly.LoadFile(System.IO.Path.Combine(path, "AWSSDK.S3.dll"));
}
return null;
}
public void Main()
{
string filePath = #"Path to file to be uploaded";
string bucket = "bllcrdtanalytics/Optimization/test"; //bucket name example
IAmazonS3 s3Client = new AmazonS3Client(Amazon.RegionEndpoint.USWest2);
PutObjectRequest putRequest = new PutObjectRequest();
putRequest.FilePath = filePath;
putRequest.Key = Path.GetFileName(filePath);
putRequest.BucketName = bucket;
PutObjectResponse response = s3Client.PutObject(putRequest);
Dts.TaskResult = (int)ScriptResults.Success;
}
}
}

Related

How to move a file in sftp using renci library?

I am attempting to move file, yet nothing happens and no exceptions are reported.
public static void MoveFiles(string source, string destination, LoginInfo loginInfo)
{
using (SftpClient sftp = new SftpClient(loginInfo.Uri, loginInfo.Port, loginInfo.User, loginInfo.Password))
{
foreach (SftpFile file in sftp.ListDirectory(source))
{
file.MoveTo(destination + file.Name);
}
}
}
The debugger simply steps out of the foreach:
What am I doing wrong?
I am using the following dependencies:
using Renci.SshNet;
using Renci.SshNet.Sftp;
You need to connect the client to the server first using
sftp.Connect();
Source
And you should also wrap it in a try-catch in case of any errors.
public static void MoveFiles(string source, string destination, LoginInfo loginInfo) {
try {
using (SftpClient sftp = new SftpClient(loginInfo.Uri, loginInfo.Port, loginInfo.User, loginInfo.Password)) {
sftp.Connect();
var files = sftp.ListDirectory(source)
foreach (SftpFile file in files) {
file.MoveTo(destination + file.Name);
}
}
} catch(Exception ex) {
//...handle
}
}

C# System.IO.IOException

I have following code:
using System;
using System.Collections.Generic;
using System.IO;
using VirusTotalNET;
using VirusTotalNET.Objects;
using System.Linq;
using System.Security.Permissions;
namespace VirusTotalNETClient
{
class Program
{
private const string ScanUrl = "http://www.google.com/";
static void Main(string[] args)
{
VirusTotal virusTotal = new VirusTotal("5d8684f50946c2bdeaf5c4fd966f61f3661de808e9d7324b99788d6f4fb7ad57");
//Use HTTPS instead of HTTP
virusTotal.UseTLS = true;
//creating folder for programs reliqies and output log
string folderName = "C:\\OnlineScanner";
System.IO.Directory.CreateDirectory(folderName);
//get list of files to analyse
var paths = Traverse("C:\test");
File.WriteAllLines("C:\\OnlineScanner\\test.txt", paths);
foreach (string line in File.ReadLines("C:\\test.txt"))
{
//Define what file you want to analyse
FileInfo fileInfo = new FileInfo(line);
//Check if the file has been scanned before.
FileReport fileReport = virusTotal.GetFileReport(fileInfo);
bool hasFileBeenScannedBefore = fileReport.ResponseCode == ReportResponseCode.Present;
//If the file has been scanned before, the results are embedded inside the report.
if (hasFileBeenScannedBefore)
{
int detekce = fileReport.Positives;
if (detekce >= 1)
{
using (var writer = new StreamWriter("C:\\OnlineScanner\\OnlineScannerLog.txt"))
{
writer.WriteLine(line);
writer.WriteLine("URL to test: " + fileReport.Permalink);
writer.WriteLine("Detect ratio: " + fileReport.Positives + "/54");
writer.WriteLine("Message: " + fileReport.VerboseMsg);
writer.WriteLine();
writer.WriteLine();
}
}
System.Threading.Thread.Sleep(16000);
}
else
{
ScanResult fileResult = virusTotal.ScanFile(fileInfo);
int detekce = fileReport.Positives;
if (detekce >= 1)
{
using (var writer = new StreamWriter("C:\\OnlineScanner\\OnlineScannerLog.txt"))
{
writer.WriteLine(line);
writer.WriteLine("URL to test: " + fileReport.Permalink);
writer.WriteLine("Detect ratio: " + fileReport.Positives + "/54");
writer.WriteLine("Message: " + fileReport.VerboseMsg);
writer.WriteLine();
writer.WriteLine();
}
}
System.Threading.Thread.Sleep(16000);
}
}
}
private static IEnumerable<string> Traverse(string rootDirectory)
{
IEnumerable<string> files = Enumerable.Empty<string>();
IEnumerable<string> directories = Enumerable.Empty<string>();
try
{
// The test for UnauthorizedAccessException.
var permission = new FileIOPermission(FileIOPermissionAccess.PathDiscovery, rootDirectory);
permission.Demand();
files = Directory.GetFiles(rootDirectory);
directories = Directory.GetDirectories(rootDirectory);
}
catch
{
// Ignore folder (access denied).
rootDirectory = null;
}
foreach (var file in files)
{
yield return file;
}
// Recursive call for SelectMany.
var subdirectoryItems = directories.SelectMany(Traverse);
foreach (var result in subdirectoryItems)
{
yield return result;
}
}
}
}
This code run some time (arround 15secs) but then program crashs.
The error is
System.IO.IOException, process can't access to file C:\hiberfil.sys.
http://upnisito.cz/images/2016_12/319crasherrror.png
Do you have any idea how to solve it?

Upload file to folder or subfolder on Sharepoint

Im trying to create a method to upload a file stream to a sharepoint so far i have this
public static void SPUploadFileStream(string username, string filePath, Stream fileData)
{
//string siteUrl = Configuration.SPSiteURL;
string siteUrl = SPContext.Current.Web.Url;
SPUser currentUser = SPUtils.GetCurrentUser(username);
if (currentUser == null)
{
throw new SPGappUnknownUserException(username);
}
using (SPSite site = new SPSite(siteUrl, currentUser.UserToken))
{
using (SPWeb web = site.OpenWeb())
{
bool allowWebUnsafeUpdt = web.AllowUnsafeUpdates;
if (!allowWebUnsafeUpdt)
web.AllowUnsafeUpdates = true;
try
{
SPCreateFolder(Path.GetDirectoryName(filePath), username);
SPFile newFile = web.Files.Add(filePath, fileData, true); //true = replace
}
catch (Exception ex)
{
LoggingService.LogError(ex);
//site.AllowUnsafeUpdates = allowSiteUnsefaUpdt;
web.AllowUnsafeUpdates = allowWebUnsafeUpdt;
throw new ApplicationException("ERROR "+ ex.ToString());
}
}
}
}
but it works ok if i have a path like "FOLDER/file.jpg" but it doesn't when i have subfolders "FOLDER/SUB/file.jpg"
can anyone give me some pointers?
My guess is that the problem lies inside your SPCreateFolder method. It should have created folders recursively. As when the you try to add new file with
SPFile newFile = web.Files.Add(filePath, fileData, true); //true = replace
the server relative path must exist. Try following method for folder creation
private static void SPCreateFolder(SPWeb web, string filepath)
{
// since you pass this as Path.GetDictionary it's no longer split by '/'
var foldersTree = filepath.Split('\\');
foldersTree.Aggregate(web.RootFolder, GetOrCreateSPFolder);
}
private static SPFolder GetOrCreateSPFolder(SPFolder sourceFolder, string folderName)
{
SPFolder destination;
try
{
// return the existing SPFolder destination if already exists
destination = sourceFolder.SubFolders[folderName];
}
catch
{
// Create the folder if it can't be found
destination = sourceFolder.SubFolders.Add(folderName);
}
return destination;
}
Then you can execute this with
...
SPCreateFolder(web, Path.GetDirectoryName(filePath));
SPFile newFile = web.Files.Add(filePath, fileData, true); //true = replace
...
Let me know if that helps

How to embed unmanaged dll into console app

Hi guys, I read lot articles about this question but nothing that I tried worked.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Reflection;
using xNet.Net;
using xNet.Collections;
namespace ConsoleApplication1
{
class Program
{
[DllImport("user32.dll")]
internal static extern bool OpenClipboard(IntPtr hWndNewOwner);
[DllImport("user32.dll")]
internal static extern bool CloseClipboard();
[DllImport("user32.dll")]
internal static extern bool SetClipboardData(uint uFormat, IntPtr data);
[STAThread]
static void Main(string[] args)
{
go();
}
public static void go()
{
CookieDictionary cookies = new CookieDictionary();
Console.WriteLine(#"[~] Trying to upload text to http://pastebin.ru/");
try
{
using (var request = new HttpRequest())
{
request.UserAgent = HttpHelper.ChromeUserAgent();
request.EnableEncodingContent = true;
request.Cookies = cookies;
request.AllowAutoRedirect = false;
var postData = new RequestParams();
postData["parent_pid"] = "";
postData["std-x"] = "1440";
postData["std-y"] = "900";
postData["poster"] = "";
postData["code_name"] = "";
postData["code"] = #"text";
postData["mode"] = "178";
postData["private"] = "1";
postData["expired"] = "1";
postData["paste"] = "Отправить";
var response = request.Post("http://pastebin.ru/", postData);
var url = response.Location;
if (string.IsNullOrEmpty(url))
{
Console.WriteLine(#"[!] Failed to upload text to http://pastebin.ru/\r\n");
Console.ReadKey();
}
else
{
url = #"http://pastebin.ru" + url;
Console.WriteLine(#"[+] Successfully uploaded to " + url);
OpenClipboard(IntPtr.Zero);
var ptr = Marshal.StringToHGlobalUni(url);
SetClipboardData(13, ptr);
CloseClipboard();
Marshal.FreeHGlobal(ptr);
}
}
}
catch (NetException ex)
{
Console.WriteLine("Net error: " + ex.Message.ToString());
}
}
}
}
I tried to add reference to dll, add it to project, changed Build Action to embedded resource, but nothing worked. Any help?
Let's call the assembly of your project MyAssembly.
Create a new folder at the root of your project in Visual Studio. Let's call it MyDlls.
Put your assembly you want to include in this folder and set their Build Action to Embedded Resource.
Then, in your code, add the following elements:
class Program
{
// ... Your code
[STAThread]
static void Main(string[] args)
{
AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolve; // Called when the assembly hasn't been successfully resolved
// ... Your code
}
private Assembly AssemblyResolve(object sender, ResolveEventArgs args)
{
Assembly assembly = Assembly.GetExecutingAssembly();
string assemblyName = args.Name.Split(',')[0]; // Gets the assembly name to resolve.
using (Stream stream = assembly.GetManifestResourceStream("MyAssembly.MyDlls." + assemblyName + ".dll")) // Gets the assembly in the embedded resources
{
if (stream == null)
return null;
byte[] rawAssembly = new byte[stream.Length];
stream.Read(rawAssembly, 0, (int)stream.Length);
return Assembly.Load(rawAssembly);
}
}
}

Creating Directories in a ZipArchive C# .Net 4.5

A ZipArchive is a collection of ZipArchiveEntries, and adding/removing "Entries" works nicely.
But it appears there is no notion of directories / nested "Archives". In theory, the class is decoupled from a file system, in that you can create the archive completely in a memory stream. But if you wish to add a directory structure within the archive, you must prefix the entry name with a path.
Question: How would you go about extending ZipArchive to create a better interface for creating and managing directories?
For example, the current method of adding a file to a directory is to create the entry with the directory path:
var entry = _archive.CreateEntry("directory/entryname");
whereas something along these lines seems nicer to me:
var directory = _archive.CreateDirectoryEntry("directory");
var entry = _directory.CreateEntry("entryname");
You can use something like the following, in other words, create the directory structure by hand:
using (var fs = new FileStream("1.zip", FileMode.Create))
using (var zip = new ZipArchive(fs, ZipArchiveMode.Create))
{
zip.CreateEntry("12/3/"); // just end with "/"
}
I know I'm late to the party (7.25.2018),
this works flawlessly to me, even with recursive directories.
Firstly, remember to install the NuGet package:
Install-Package System.IO.Compression
And then, Extension file for ZipArchive:
public static class ZipArchiveExtension {
public static void CreateEntryFromAny(this ZipArchive archive, string sourceName, string entryName = "") {
var fileName = Path.GetFileName(sourceName);
if (File.GetAttributes(sourceName).HasFlag(FileAttributes.Directory)) {
archive.CreateEntryFromDirectory(sourceName, Path.Combine(entryName, fileName));
} else {
archive.CreateEntryFromFile(sourceName, Path.Combine(entryName, fileName), CompressionLevel.Fastest);
}
}
public static void CreateEntryFromDirectory(this ZipArchive archive, string sourceDirName, string entryName = "") {
string[] files = Directory.GetFiles(sourceDirName).Concat(Directory.GetDirectories(sourceDirName)).ToArray();
archive.CreateEntry(Path.Combine(entryName, Path.GetFileName(sourceDirName)));
foreach (var file in files) {
archive.CreateEntryFromAny(file, entryName);
}
}
}
And then you can pack anything, whether it is file or directory:
using (var memoryStream = new MemoryStream()) {
using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true)) {
archive.CreateEntryFromAny(sourcePath);
}
}
If you are working on a project that can use full .NET you may try to use
the ZipFile.CreateFromDirectory method, as explained here:
using System;
using System.IO;
using System.IO.Compression;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
string startPath = #"c:\example\start";
string zipPath = #"c:\example\result.zip";
string extractPath = #"c:\example\extract";
ZipFile.CreateFromDirectory(startPath, zipPath, CompressionLevel.Fastest, true);
ZipFile.ExtractToDirectory(zipPath, extractPath);
}
}
}
Of course this will only work if you are creating new Zips based on a given directory.
As per the comment, the previous solution does not preserve the directory structure. If that is needed, then the following code might address that:
var InputDirectory = #"c:\example\start";
var OutputFilename = #"c:\example\result.zip";
using (Stream zipStream = new FileStream(Path.GetFullPath(OutputFilename), FileMode.Create, FileAccess.Write))
using (ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Create))
{
foreach(var filePath in System.IO.Directory.GetFiles(InputDirectory,"*.*",System.IO.SearchOption.AllDirectories))
{
var relativePath = filePath.Replace(InputDirectory,string.Empty);
using (Stream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
using (Stream fileStreamInZip = archive.CreateEntry(relativePath).Open())
fileStream.CopyTo(fileStreamInZip);
}
}
Here is one possible solution:
public static class ZipArchiveExtension
{
public static ZipArchiveDirectory CreateDirectory(this ZipArchive #this, string directoryPath)
{
return new ZipArchiveDirectory(#this, directoryPath);
}
}
public class ZipArchiveDirectory
{
private readonly string _directory;
private ZipArchive _archive;
internal ZipArchiveDirectory(ZipArchive archive, string directory)
{
_archive = archive;
_directory = directory;
}
public ZipArchive Archive { get{return _archive;}}
public ZipArchiveEntry CreateEntry(string entry)
{
return _archive.CreateEntry(_directory + "/" + entry);
}
public ZipArchiveEntry CreateEntry(string entry, CompressionLevel compressionLevel)
{
return _archive.CreateEntry(_directory + "/" + entry, compressionLevel);
}
}
and used:
var directory = _archive.CreateDirectory(context);
var entry = directory.CreateEntry(context);
var stream = entry.Open();
but I can foresee problems with nesting, perhaps.
I was also looking for a similar solution and found #Val & #sDima's solution more promising to me. But I found some issues with the code and fixed them to use with my code.
Like #sDima, I also decided to use Extension to add more functionality to ZipArchive.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Compression;
using System.IO;
namespace ZipTest
{
public static class ZipArchiveExtensions
{
public static void CreateEntryFromAny(this ZipArchive archive, string sourceName, string entryName, CompressionLevel compressionLevel = CompressionLevel.Optimal)
{
try
{
if (File.GetAttributes(sourceName).HasFlag(FileAttributes.Directory))
{
archive.CreateEntryFromDirectory(sourceName, entryName, compressionLevel);
}
else
{
archive.CreateEntryFromFile(sourceName, entryName, compressionLevel);
}
}
catch
{
throw;
}
}
public static void CreateEntryFromDirectory(this ZipArchive archive, string sourceDirName, string entryName, CompressionLevel compressionLevel)
{
try
{
var files = Directory.EnumerateFileSystemEntries(sourceDirName);
if (files.Any())
{
foreach (var file in files)
{
var fileName = Path.GetFileName(file);
archive.CreateEntryFromAny(file, Path.Combine(entryName, fileName), compressionLevel);
}
}
else
{
//Do a folder entry check.
if (!string.IsNullOrEmpty(entryName) && entryName[entryName.Length - 1] != '/')
{
entryName += "/";
}
archive.CreateEntry(entryName, compressionLevel);
}
}
catch
{
throw;
}
}
}
}
You can try the extension using the simple given below,
class Program
{
static void Main(string[] args)
{
string filePath = #"C:\Users\WinUser\Downloads\Test.zip";
string dirName = Path.GetDirectoryName(filePath);
if (File.Exists(filePath))
File.Delete(filePath);
using (ZipArchive archive = ZipFile.Open(filePath, ZipArchiveMode.Create))
{
archive.CreateEntryFromFile( #"C:\Users\WinUser\Downloads\file1.jpg", "SomeFolder/file1.jpg", CompressionLevel.Optimal);
archive.CreateEntryFromDirectory(#"C:\Users\WinUser\Downloads\MyDocs", "OfficeDocs", CompressionLevel.Optimal);
archive.CreateEntryFromAny(#"C:\Users\WinUser\Downloads\EmptyFolder", "EmptyFolder", CompressionLevel.Optimal);
};
using (ZipArchive zip = ZipFile.OpenRead(filePath))
{
string dirExtract = #"C:\Users\WinUser\Downloads\Temp";
if (Directory.Exists(dirExtract))
{
Directory.Delete(dirExtract, true);
}
zip.ExtractToDirectory(dirExtract);
}
}
}
I tried to keep the exact behavior of standard CreateEntryFromFilefrom the .Net Framework for extension methods.
To use the sample code given, add a reference to System.IO.Compression.dll and System.IO.Compression.FileSystem.dll.
Following are the advantages of this extension class
Recursive adding of folder content.
Support for an empty folder.
My answer is based on the Val's answer, but a little improved for performance and without producing empty files in ZIP.
public static class ZipArchiveExtensions
{
public static void CreateEntryFromAny(this ZipArchive archive, string sourceName, string entryName = "")
{
var fileName = Path.GetFileName(sourceName);
if (File.GetAttributes(sourceName).HasFlag(FileAttributes.Directory))
{
archive.CreateEntryFromDirectory(sourceName, Path.Combine(entryName, fileName));
}
else
{
archive.CreateEntryFromFile(sourceName, Path.Combine(entryName, fileName), CompressionLevel.Optimal);
}
}
public static void CreateEntryFromDirectory(this ZipArchive archive, string sourceDirName, string entryName = "")
{
var files = Directory.EnumerateFileSystemEntries(sourceDirName);
foreach (var file in files)
{
archive.CreateEntryFromAny(file, entryName);
}
}
}
Example of using:
// Create and open a new ZIP file
using (var zip = ZipFile.Open(ZipPath, ZipArchiveMode.Create))
{
foreach (string file in FILES_LIST)
{
// Add the entry for each file
zip.CreateEntryFromAny(file);
}
}
One more tuned ZipArchive extension, which adds folder structure including all subfolders and files to zip. Solved IOException (Process can't access the file...) which is thrown if files are in use at zipping moment, for example by some logger
public static class ZipArchiveExtensions
{
public static void AddDirectory(this ZipArchive #this, string path)
{
#this.AddDirectory(path, string.Empty);
}
private static void AddDirectory(this ZipArchive #this, string path, string relativePath)
{
var fileSystemEntries = Directory.EnumerateFileSystemEntries(path);
foreach (var fileSystemEntry in fileSystemEntries)
{
if (File.GetAttributes(fileSystemEntry).HasFlag(FileAttributes.Directory))
{
#this.AddDirectory(fileSystemEntry, Path.Combine(relativePath, Path.GetFileName(fileSystemEntry)));
continue;
}
var fileEntry = #this.CreateEntry(Path.Combine(relativePath, Path.GetFileName(fileSystemEntry)));
using (var zipStream = fileEntry.Open())
using (var fileStream = new FileStream(fileSystemEntry, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var memoryStream = new MemoryStream())
{
fileStream.CopyTo(memoryStream);
var bytes = memoryStream.ToArray();
zipStream.Write(bytes, 0, bytes.Length);
}
}
}
}
A little change in the very good approach from #Andrey
public static void CreateEntryFromDirectory2(this ZipArchive archive, string sourceDirName, CompressionLevel compressionLevel = CompressionLevel.Fastest)
{
var folders = new Stack<string>();
folders.Push(sourceDirName);
do
{
var currentFolder = folders.Pop();
foreach (var item in Directory.GetFiles(currentFolder))
{
archive.CreateEntryFromFile(item, item.Substring(sourceDirName.Length + 1), compressionLevel);
}
foreach (var item in Directory.GetDirectories(currentFolder))
{
folders.Push(item);
}
}
while (folders.Count > 0);
}
Use the recursive approach to Zip Folders with Subfolders.
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
public static async Task<bool> ZipFileHelper(IFolder folderForZipping, IFolder folderForZipFile, string zipFileName)
{
if (folderForZipping == null || folderForZipFile == null
|| string.IsNullOrEmpty(zipFileName))
{
throw new ArgumentException("Invalid argument...");
}
IFile zipFile = await folderForZipFile.CreateFileAsync(zipFileName, CreationCollisionOption.ReplaceExisting);
// Create zip archive to access compressed files in memory stream
using (MemoryStream zipStream = new MemoryStream())
{
using (ZipArchive zip = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
{
await ZipSubFolders(folderForZipping, zip, "");
}
zipStream.Position = 0;
using (Stream s = await zipFile.OpenAsync(FileAccess.ReadAndWrite))
{
zipStream.CopyTo(s);
}
}
return true;
}
//Create zip file entry for folder and subfolders("sub/1.txt")
private static async Task ZipSubFolders(IFolder folder, ZipArchive zip, string dir)
{
if (folder == null || zip == null)
return;
var files = await folder.GetFilesAsync();
var en = files.GetEnumerator();
while (en.MoveNext())
{
var file = en.Current;
var entry = zip.CreateEntryFromFile(file.Path, dir + file.Name);
}
var folders = await folder.GetFoldersAsync();
var fEn = folders.GetEnumerator();
while (fEn.MoveNext())
{
await ZipSubFolders(fEn.Current, zip, dir + fEn.Current.Name + "/");
}
}
I don't like recursion as it was proposed by #Val, #sDima, #Nitheesh. Potentially it leads to the StackOverflowException because the stack has limited size. So here is my two cents with tree traversal.
public static class ZipArchiveExtensions
{
public static void CreateEntryFromDirectory(this ZipArchive archive, string sourceDirName, CompressionLevel compressionLevel = CompressionLevel.Fastest)
{
var folders = new Stack<string>();
folders.Push(sourceDirName);
do
{
var currentFolder = folders.Pop();
Directory.GetFiles(currentFolder).ForEach(f => archive.CreateEntryFromFile(f, f.Substring(sourceDirName.Length+1), compressionLevel));
Directory.GetDirectories(currentFolder).ForEach(d => folders.Push(d));
} while (folders.Count > 0);
}
}
It's working for me.
Static class
public static class ZipArchiveExtension
{
public static void CreateEntryFromAny(this ZipArchive archive, string sourceName, string entryName = "")
{
var fileName = Path.GetFileName(sourceName);
if (File.GetAttributes(sourceName).HasFlag(FileAttributes.Directory))
{
archive.CreateEntryFromDirectory(sourceName, Path.Combine(entryName, fileName));
}
else
{
archive.CreateEntryFromFile(sourceName, Path.Combine(entryName, fileName), CompressionLevel.Fastest);
}
}
public static void CreateEntryFromDirectory(this ZipArchive archive, string sourceDirName, string entryName = "")
{
string[] files = Directory.GetFiles(sourceDirName).Concat(Directory.GetDirectories(sourceDirName)).ToArray();
if (files.Any())
{
foreach (var file in files)
{
archive.CreateEntryFromAny(file, entryName);
}
}
else
{
if (!string.IsNullOrEmpty(entryName) && entryName[entryName.Length - 1] != '/')
{
entryName += "\\";
}
archive.CreateEntry(entryName);
}
}
}
Calling the method like that
byte[] archiveFile;
using (var memoryStream = new MemoryStream())
{
using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
archive.CreateEntryFromAny(file.Path);
}
archiveFile = memoryStream.ToArray();
}

Categories

Resources