I am trying to enumerate the zipped folders that are inside an unzipped folder using Directory.GetDirectories(folderPath).
The problem I have is that it does not seem to be finding the zipped folders, when I come to iterate over the string[], it is empty.
Is Directory.GetDirectories() the wrong way to go about this and if so what method serves this purpose?
Filepath example: C:\...\...\daily\daily\{series of zipped folder}
public void CheckZippedDailyFolder(string folderPath)
{
if(folderPath.IsNullOrEmpty())
throw new Exception("Folder path required");
foreach (var folder in Directory.GetDirectories(folderPath))
{
var unzippedFolder = Compression.Unzip(folder + ".zip", folderPath);
using (TextReader reader = File.OpenText(unzippedFolder + #"\" + new DirectoryInfo(folderPath).Name))
{
var csv = new CsvReader(reader);
var field = csv.GetField(0);
Console.WriteLine(field);
}
}
}
GetDirectories is the wrong thing to use. Explorer lies to you; zip files are actually files with an extension .zip, not real directories on the file system level.
Look at:
https://msdn.microsoft.com/en-us/library/system.io.compression.ziparchive.entries%28v=vs.110%29.aspx (ZipArchive.Entries) and/or
https://msdn.microsoft.com/en-us/library/system.io.compression.zipfile%28v=vs.110%29.aspx (ZipFile) to see how to deal with them.
Related
I have files stored in multiple different folders and I need to make a ZIP archive from all the files in those folders. I have created a simple function using System.IO.Compression, that takes the data from just one folder and makes a ZIP archive, but I can't figure out how to do that for multiple folders. No folders needed in ZIP, just the files from it.
If it can't be done in this library, I can use a different one like DotNetZip or similar.
string folder1 = #"c:\ex\ZipFolder1";
string zipPath = #"c:\ex\AllFiles.zip";
ZipFile.CreateFromDirectory(folder1, zipPath);
I think you're using DotNetZip.Just create a ZipFile and add files by the method AddFiles
using (var file = new ZipFile())
{
//fileNames is an array containing the paths of the files from differents folders
file.AddFiles(fileNames);
file.Save(zipFile);
}
Have you tried using AddFile() method of ZipFile Class. Here you can replace 'PathOfFiles' dynamically as per your requirement.
var fileNames = new string[] { "a.txt", "b.xlsx", "c.png" };
using (var zip = new ZipFile()){
foreach (var file in fileNames)
zip.AddFile(#"PathOfFiles\" + fileName, "");
zip.Name = "ZipFile";
var pushStreamContent = new PushStreamContent((stream, content, context) =>
{
zip.Save(stream);
stream.Close();
}, "application/zip");
}
for anyone encountering this today, here's an updated short and simple answer based on Microsoft's docs:
https://learn.microsoft.com/en-us/dotnet/api/system.io.compression.zipfileextensions.createentryfromfile?view=net-6.0
static void SaveFilesToZip(string zipTargetPath, string[] filePaths)
{
using var newZip = ZipFile.Open(zipTargetPath, ZipArchiveMode.Create);
foreach (var filePath in filePaths)
{
newZip.CreateEntryFromFile(filePath, Path.GetFileName(filePath));
}
}
I am looking to read folders and files from a directory structure like so..
e.g
C:\RootFolder
SubFolder1
SubFolder2
File1
File2
SubFolder3
File3
Files....
Files....
I would like to read both, files and folders and write to another directory I cant use copy , because the directory I want to write to is remote and not local.
I read the files here.... Id love to be able to read folders and files and write both to another directory.
public static IEnumerable<FileInfo> GetFiles(string dir)
{
return Directory.EnumerateFiles(dir, "*", SearchOption.AllDirectories)
.Select(path =>
{
var stream = File.OpenRead(path);
return new FileInfo(Path.GetFileName(path), stream);
})
.DisposeEach(c => c.Content);
}
this function writes files to a remote sftp site.
public Task Write(IEnumerable<FileInfo> files)
{
return Task.Run(() =>
{
using (var sftp = new SftpClient(this.sshInfo))
{
sftp.Connect();
sftp.ChangeDirectory(this.remoteDirectory);
foreach (var file in files)
{
sftp.UploadFile(file.Content, file.RelativePath);
}
}
});
}
In this function I write the read files from the above function.
private async static Task SendBatch(Config config, Batch batch, IRemoteFileWriter writer)
{
var sendingDir = GetClientSendingDirectory(config, batch.ClientName);
Directory.CreateDirectory(Path.GetDirectoryName(sendingDir));
Directory.Move(batch.LocalDirectory, sendingDir);
Directory.CreateDirectory(batch.LocalDirectory);
//Use RemoteFileWriter...
var files = GetFiles(sendingDir);
await writer.Write(files).ContinueWith(t =>
{
if(t.IsCompleted)
{
var zipArchivePath = GetArchiveDirectory(config, batch);
ZipFile.CreateFromDirectory(
sendingDir,
zipArchivePath + " " +
DateTime.Now.ToString("yyyy-MM-dd hh mm ss.Zip")
);
}
});
}
Thank you!
You are getting UnauthorizedAccessException: Access to the path 'C:\temp' is denied. because you can't open a stream from a folder as it doesn't contain bytes.
From what I can understand you are looking to copy the files from one folder to another.
This answer seems to cover what you are doing. https://stackoverflow.com/a/3822913/3634581
Once you have copied the directories you can then create the zip file.
If you don't need to copy the files and just create the Zip I would recommend that since it will reduce the disk IO and speed up the process.
ZipArchive (https://msdn.microsoft.com/en-us/library/system.io.compression.ziparchive(v=vs.110).aspx) can be used to create a zip file straight to a stream.
I figured it out here is the solution
public Task Write(IEnumerable<FileInfo> files)
{
return Task.Run(() =>
{
using (var sftp = new SftpClient(this.sshInfo))
{
sftp.Connect();
sftp.ChangeDirectory(this.remoteDirectory);
foreach (var file in files)
{
var parts = Path.GetDirectoryName(file.RelativePath)
.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
sftp.ChangeDirectory(this.remoteDirectory);
foreach (var p in parts)
{
try
{
sftp.ChangeDirectory(p);
}
catch (SftpPathNotFoundException)
{
sftp.CreateDirectory(p);
sftp.ChangeDirectory(p);
}
}
sftp.UploadFile(file.Content, Path.GetFileName(file.RelativePath));
}
}
});
}
****Key point to the solution was
this
var parts = Path.GetDirectoryName(file.RelativePath)
.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
We call *Path.GetDirectoryName
on the file itself to get the directory that correlates to the file.
We split the file directory to get the folder name and finally create the folder name we obtained from the split and upload the file to it.
I hope this helps others who may encounter such issue.
I have no problems when I want to create a new folder
I'm working with
Directory.CreateDirectory
Now I'm trying to get all image files from my desktop and I want to move all images to that folder which was created with Directory.CreateDirectory
I've testet file.MoveTo
from here
FileInfo file = new FileInfo(#"C:\Users\User\Desktop\test.txt");
to here
file.MoveTo(#"C:\Users\User\Desktop\folder\test.txt");
This works perfect.
Now I want to do that with all the image files from my dekstop
(Directory.CreateDirectory(#"C:\Users\User\Desktop\Images");)
How could I do that?
Example code of getting images with certain extentions from one root folder:
static void Main(string[] args)
{
// path to desktop
var desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
//get file extentions by speciging the needed extentions
var images = GetFilesByExtensions(new DirectoryInfo(desktopPath) ,".png", ".jpg", ".gif");
// loop thrue the found images and it will copy it to a folder (make sure the folder exists otherwise filenot found exception)
foreach (var image in images)
{
// if you want to move it to another directory without creating a copy use:
image.MoveTo(desktopPath + "\\folder\\" + image.Name);
// if you want to move a copy of the image use this
File.Copy(desktopPath + "\\"+ image.Name, desktopPath + "\\folder\\" + image.Name, true);
}
}
public static IEnumerable<FileInfo> GetFilesByExtensions(DirectoryInfo dir, params string[] extensions)
{
if (extensions == null)
throw new ArgumentNullException("extensions");
var files = dir.EnumerateFiles();
return files.Where(f => extensions.Contains(f.Extension));
}
Please try this:
You can filter files in a specific directory and then looop through search results to move each file, you might be able to modify search pattern to match on a number of different image file formats
var files = Directory.GetFiles("PathToDirectory", "*.jpg");
foreach (var fileFound in files)
{
//Move your files one by one here
FileInfo file = new FileInfo(fileFound);
file.MoveTo(#"C:\Users\User\Desktop\folder\" + file.Name);
}
I am using .NET 2.0 and Linq is out of question. I would like to check if file exists inside a directory without knowledge of the file extension.
I just need this logic done.
1.Check File exists in Directory using String Filename provided using search pattern leaving out the extension of the File
2.Get the Files if they exists and Databind to provide Download links.If file does not exist then start uploading the File.
Update:
Directory.GetFiles() and DirectoryInfo.GetFiles() indeed solves the part where in i check for File existence. As for the performance regarding FileInfo objects, these were only solution to my requirements of databinding to provide download links
DirectoryInfo root = new DirectoryInfo("your_directory_path");
FileInfo[] listfiles = root.GetFiles("dummy.*");
if (listfiles.Length > 0)
{
//File exists
foreach (FileInfo file in listfiles)
{
//Get Filename and link download here
}
}
else
{
//File does not exist
//Upload
}
Hope this works
To see if a file exists with that name, can you not just use..
However, Directory.GetFiles already includes the full path
string [] files = Directory.GetFiles(Path,"name*");
bool exists = files.Length > 0;
if ( exists)
{
//Get file info - assuming only one file here..
FileInfo fi = new FileInfo(files[0]);
//Or loop through all files
foreach (string s in files)
{
FileInfo fi = new FileInfo(s);
//Do something with fileinfo
}
}
You can use DirectoryInfo.GetFiles() to have a FileInfo[] instead of a String[].
I want to pack a directory in C# using Ionic Zip. Normally I would just use this piece of code:
using (ZipFile pack = new ZipFile())
{
pack.AddDirectory(defPackageCreationPath + "\\installfiles", "");
pack.Save(outputPath + "\\package.mpp");
}
This is working fine, however I need to iterate through each file being packed to check for characters in their filenames, as I have some files that gets corrupted when packed, if they contain specific characters.
What is important too is that the directory to add contains sub directories too, and those needs to be carried over to the zip file and created inside it.
How?
Not sure if this is what you are looking for but you can easily get a string array of all files including sub directories. using the Directory class
Like so
string[] Files = Directory.GetFiles(#"M:\Backup", "*.*", SearchOption.AllDirectories);
foreach (string file in Files)
{
DoTests(file);
}
This will include the path to the files.
You will need System.IO;
using System.IO;
You can also try something like this:
using (ZipFile pack = new ZipFile())
{
pack.AddProgress += (s, eventArgs) =>
{
// check if EventType is Adding_AfterAddEntry or NullReferenceException will be thrown
if (eventArgs.EventType == ZipProgressEventType.Adding_AfterAddEntry)
{
// Do the replacement here.
// eventArgs.CurrentEntry is the current file processed and
// eventArgs.CurrentEntry.FileName holds the file name
//
// Example: all files will begin with __
eventArgs.CurrentEntry.FileName = "___" + eventArgs.CurrentEntry.FileName;
}
};
pack.AddDirectory(defPackageCreationPath + "\\installfiles", "");
pack.Save(outputPath + "\\package.mpp");
}
}