I need some help.
I just have this code right now. This code is working, but it's not enough.
My code;
DirectoryInfo dirFile = new DirectoryInfo(currentDir);
FileInfo[] infoFile = dirFile.GetFiles("*.zip", SearchOption.AllDirectories);
foreach (FileInfo currentFile in infoFile)
{
using (ZipFile zipFile = ZipFile.Read(currentFile.FullName))
{
zipFile.ExtractProgress += new EventHandler<ExtractProgressEventArgs>(unZipFiles_ExtractProgressChanged);
foreach (ZipEntry currentZip in zipFile)
{ currentZip.Extract(currentFile.DirectoryName, ExtractExistingFileAction.OverwriteSilently); }
}
currentCount = increaseCount + 1; increaseCount = currentCount;
if (downloadType == 1) { bar2SetProgress((ulong)currentCount, (ulong)totalCount); }
lblFileName.Text = currentFile.Name;
}
I want to extract all zip files to Application.StartupPath folder from _ZipFiles folder with all subdirectories.
Here is one example;
I have one zip folder. Name: _ZipFolder
Before the unzip process;
Application.StartupPath\_ZipFiles\startProgram.zip
Application.StartupPath\_ZipFiles\updateProgram.zip
Application.StartupPath\_ZipFiles\Pack\testDownload.zip
Application.StartupPath\_ZipFiles\Pack\Version\repo2.zip
Application.StartupPath\_ZipFiles\Pack\Version\newClass.zip
Application.StartupPath\_ZipFiles\Ack\Library\argSetup.zip
Application.StartupPath\_ZipFiles\Ack\learnMachine.zip
Application.StartupPath\_ZipFiles\Code\zipVersion4.zip
After the unzip process (I exactly want to this extract);
Application.StartupPath\startProgram.exe
Application.StartupPath\updateProgram.exe
Application.StartupPath\Pack\testDownload.exe
Application.StartupPath\Pack\Version\repo2.cs
Application.StartupPath\Pack\Version\newClass.cs
Application.StartupPath\Ack\Library\argSetup.exe
Application.StartupPath\Ack\learnMachine.pdf
Application.StartupPath\Code\zipVersion4.exe
All files needs move to Application.StartupPath from _ZipFiles folder with subdirectories.
How to make this? Please help me.
I hope you understand what I want. I'm sorry for my bad English.
Remove the zip folder name from the current file directory name when extracting
Based on current example where you have _ZipFiles folder
DirectoryInfo dirFile = new DirectoryInfo(currentDir);
FileInfo[] infoFile = dirFile.GetFiles("*.zip", SearchOption.AllDirectories);
var zipFolderName = #"\_ZipFiles";
foreach (FileInfo currentFile in infoFile) {
using (ZipFile zipFile = ZipFile.Read(currentFile.FullName)) {
zipFile.ExtractProgress += new EventHandler<ExtractProgressEventArgs>(unZipFiles_ExtractProgressChanged);
var destination = currentFile.DirectoryName.Replace(zipFolderName, "");
foreach (ZipEntry currentZip in zipFile) {
currentZip.Extract(destination, ExtractExistingFileAction.OverwriteSilently);
}
}
currentCount = increaseCount + 1; increaseCount = currentCount;
if (downloadType == 1) { bar2SetProgress((ulong)currentCount, (ulong)totalCount); }
lblFileName.Text = currentFile.Name;
}
If I understood you correctly, you want to extract all files to Application.StartupPath directory instead in subfolders.
Try to change:
currentZip.Extract(currentFile.DirectoryName, ExtractExistingFileAction.OverwriteSilently);
to
currentZip.Extract(Application.StartupPath, ExtractExistingFileAction.OverwriteSilently);
If Application.StartupPath isn't suitable, then maybe use AppDomain.CurrentDomain.BaseDirectory
Related
I have 1 folder that contains many txt files. I want to zip them but separated.
Example:
In this folder I have A.txt, B.txt, C.txt.
I want to zip all the files but separated so the result will be A.zip, B.zip, C.zip.
string outputPath = "C:\\Users\\Desktop\\VA";
string path = outputPath + "\\VA_" + tglskrg;
foreach (string dirFile in Directory.GetDirectories(path))
{
foreach (string fileName in Directory.GetFiles(dirFile))
{
using (ZipFile zip = new ZipFile())
{
zip.UseUnicodeAsNecessary = true;
zip.AddFile(); //dont know what to put
zip.Save(); //dont know what to put
}
}
}
Any help will be appreciated.
I'm using dotnetzip (Ionic.zip) and C# Visual Studio Express 2010.
You could do that as follows:
foreach (string fileName in Directory.GetFiles(dirFile))
{
var zipFile = Path.Combine(outputPath, Path.ChangeExtension(fileName, ".zip"));
using (ZipFile zip = new ZipFile())
{
zip.AddFile(fileName); // add A.txt to the zip file
zip.Save(zipFile); // save as A.zip
}
}
This takes all the files found in the folder dirFile, and saves them under outputPath, with the same file name but replacing the extension with .zip.
One Question about coding (Visual Studio C# Windows form Application) There have Two folder: (Source and Target) and I build 1 button "Copy". In (Source) folder have random folders such "20190401", "20190402", "20190403", "20180401", "20170401" and "20160401". Every these folders have [10] ".txt" files. What is the coding if I only want to copy all "201904**" folders with [3] ".txt" files inside to "Target" folder?
Here my code for now, after I click a button the folder wouldn't copy. I guess there have some problem with this codes and I still not found it until. Hope you guys can help me, thank you.
*namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string FROM_DIR = "C:/Users/Desktop/Source/";
string TO_DIR = "C:/Users/Desktop/Target/";
DirectoryInfo diCopyForm = new DirectoryInfo(FROM_DIR);
DirectoryInfo[] fiDiskfiles = diCopyForm.GetDirectories();
string directname = "201904";
string filename = ".txt";
foreach (DirectoryInfo newfile in fiDiskfiles)
{
try
{
if (newfile.Name == "2019")
{
foreach (DirectoryInfo direc in newfile.GetDirectories())
if (direc.Name.StartsWith(directname))
{
int count = 0;
foreach (FileInfo file in direc.GetFiles())
{
if (file.Name.EndsWith(filename))
{
count++;
}
}
if (count == 3)
{
DirectoryCopy(direc.FullName,Path.Combine(TO_DIR,direc.Name), true);
count = 0;
MessageBox.Show("success");
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException("Source directory does not exist or could not be found: "+ sourceDirName);
}
DirectoryInfo[] dirs = dir.GetDirectories();
// 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 = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
}
*}
By clicking the button, automatically copy all "201904**" folder and 3 ".txt files in (Source) folder to (target folder).
You didn't say which 3 txt files you want to copy so the code below copies all txt files, please explain how you select the files and I'll edit the code.
const string Source = #"C:\Users\Desktop\Source\";
const string Target = #"C:\Users\Desktop\Target\";
const string StartsWith = "201904";
const string FileType = "txt";
public static void Copy()
{
if (!Directory.Exists(Source)) //Check if the source directory exists
throw new Exception("Source directory is missing!");
Directory.CreateDirectory(Target); //If the target directory doesn't exists it will create one
var Directories = Directory.GetDirectories(Source, $"{StartsWith}*"); //Get directories which match the search pattern
for (int i = 0; i < Directories.Length; i++)
{
DirectoryInfo directory = new DirectoryInfo(Directories[i]);
Directory.CreateDirectory($"{Target}{directory.Name}"); //Create the directory in the target folder
var Files = Directory.GetFiles($"{Source}{directory.Name}", $"*.{FileType}"); //Get files
for (int j = 0; j < Files.Length; j++)
{
FileInfo file = new FileInfo(Files[j]);
File.Copy($"{Source}{directory.Name}" + #"\" + file.Name, $"{Target}{directory.Name}" + #"\" + file.Name); //Copy the file to the target folder
}
}
}
This code selects all directories which start with "201904" and all txt files inside them and copies it to the target folder.
EDIT: Fixed a mistake in the code
I am able to zip files from a specific folder using ZipFile.CreateFromDirectory in the following test code (I only used this code to test how zipping works):
// Where the files are located
string strStartPath = txtTargetFolder.Text;
// Where the zip file will be placed
string strZipPath = #"C:\Users\smelmo\Desktop\testFinish\" + strFileNameRoot + "_" + txtDateRange1.Text.Replace(#"/", "_") + "_" + txtDateRange2.Text.Replace(#"/", "_") + ".zip";
ZipFile.CreateFromDirectory(strStartPath, strZipPath);
However, this zips together ALL of the contents in the folder. I am trying to zip together specific items in the folder using ZipArchive in the following code:
// Where the files are located
string strStartPath = txtTargetFolder.Text;
// Where the zip file will be placed
string strZipPath = #"C:\Users\smelmo\Desktop\testFinish\" + strFileNameRoot + "_" + txtDateRange1.Text.Replace(#"/", "_") + "_" + txtDateRange2.Text.Replace(#"/", "_") + ".zip";
using (ZipArchive archive = ZipFile.OpenRead(strStartPath))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
if (!(entry.FullName.EndsWith(".TIF", StringComparison.OrdinalIgnoreCase)))
{
entry.ExtractToFile(Path.Combine(strZipPath, entry.FullName));
}
}
}
It is giving the error at ZipFile.OpenRead(strStartPath). Why am I able to access the exact folder in the first block of code but not the second? Or is there an easier way to search through a folder and only zip specific items?
You are utilizing the Zip libraries wrong
Effectively you are trying to open a directory as if it were a zip file, then loop over the contents of that directory (which again is actually a zip file) and then attempting to extract each member into a different zip file
Here is a working example of what you have described you are trying to do:
string strStartPath = #"PATH TO FILES TO PUT IN ZIP FILE";
string strZipPath = #"PATH TO ZIP FILE";
if (File.Exists(strZipPath))
File.Delete(strZipPath);
using (ZipArchive archive = ZipFile.Open(strZipPath, ZipArchiveMode.Create))
{
foreach (FileInfo file in new DirectoryInfo(strStartPath).GetFiles())
{
if (!(file.FullName.EndsWith(".TIF", StringComparison.OrdinalIgnoreCase)))
{
archive.CreateEntryFromFile(Path.Combine(file.Directory.ToString(), file.Name), file.Name);
}
}
}
This will take all the root level contents of a folder and put it in the zip file. You will need to implement your own way of getting subfolders and their contents recursively, but that is beyond the scope of this question.
EDIT: Here is a working example with proper folder recursion to select all files even in subdirectories
public void ZipFolder()
{
string strStartPath = #"PATH TO FILES TO PUT IN ZIP FILE";
string strZipPath = #"PATH TO ZIP FILE";
if (File.Exists(strZipPath))
File.Delete(strZipPath);
using (ZipArchive archive = ZipFile.Open(strZipPath, ZipArchiveMode.Create))
{
foreach (FileInfo file in RecurseDirectory(strStartPath))
{
if (!(file.FullName.EndsWith(".TIF", StringComparison.OrdinalIgnoreCase)))
{
var destination = Path.Combine(file.DirectoryName, file.Name).Substring(strStartPath.Length + 1);
archive.CreateEntryFromFile(Path.Combine(file.Directory.ToString(), file.Name), destination);
}
}
}
}
public IEnumerable<FileInfo> RecurseDirectory(string path, List<FileInfo> currentData = null)
{
if (currentData == null)
currentData = new List<FileInfo>();
var directory = new DirectoryInfo(path);
foreach (var file in directory.GetFiles())
currentData.Add(file);
foreach (var d in directory.GetDirectories())
RecurseDirectory(d.FullName, currentData);
return currentData;
}
I have implemented a code like this from which I got the idea somewhere.
public string BrowseFolder()
{
string filePath = string.Empty;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Multiselect = true;
openFileDialog1.Title = "Browse EXCEL File";
openFileDialog1.Filter = "Excel Files (*.xlsx)|*.xlsx";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
filePath = openFileDialog1.FileName;
return Path.GetDirectoryName(filePath);
}
return null;
}
public void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
// If the source directory does not exist, throw an exception.
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
// If the destination directory does not exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the file contents of the directory to copy.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
// Create the path to the new copy of the file.
string temppath = Path.Combine(destDirName, file.Name.ToString());
// Copy the file.
file.CopyTo(temppath, false);
}
// If copySubDirs is true, copy the subdirectories.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
// Create the subdirectory.
string temppath = Path.Combine(destDirName, subdir.Name);
// Copy the subdirectories.
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
Ok let's assume that this two methods is in a class. I have easily understood how this codes work. It is copying all the files inside the folder I browse. This is not what I need. What I wanted to achieve is to copy only the selected files (multiple) in my folder.
I've tried to manipulate my code but I still didn't get the right solution. Thanks in advance.
foreach (string file in openFileDialog1.FileNames)
{
FileInfo fInfo = new FileInfo(file);
fInfo.MoveTo(newFilePath);
}
Ref: https://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.filenames(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.io.fileinfo.moveto(v=vs.110).aspx
You need to get all the files selected from OpenFileDialog like this:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string[] filesSelected = openFileDialog1.FileNames;
}
The code above returns all the files that a user selected from the OpenFileDialog.
how do i allow this code to retrieve the files from a directory? For example, my directory name is "Folder Name":
private ObservableCollection<FileItem> LoadFiles()
{
ObservableCollection<FileItem> files = new ObservableCollection<FileItem>();
foreach (string filePath in this.Store.GetFileNames())
files.Add(new FileItem { FileName = filePath });
return files;
}
EDIT:
I've tried this, and it still isn't working:
private ObservableCollection<FileItem> LoadFiles()
{
ObservableCollection<FileItem> files = new ObservableCollection<FileItem>();
foreach (string filePath in this.Store.GetFileNames())
files.Add(new FileItem { "FlashCardApp\\" + FileName = filePath });
return files;
}
I've finally found the answer to my own question.
This is how it is suppose to be:
private ObservableCollection<FileItem> LoadFiles()
{
ObservableCollection<FileItem> files = new ObservableCollection<FileItem>();
foreach (string filePath in this.Store.GetFileNames("FlashCardApp\\"))
files.Add(new FileItem { FileName = filePath });
return files;
}
By having \ after the folder name, "FlashCardApp\\", it will retrieve the files from the directory.
DirectoryInfo di = new DirectoryInfo("c:/Folder Name");
FileInfo[] rgFiles = di.GetFiles("*.*");
foreach(FileInfo fi in rgFiles)
{
//Do something
fi.Name
}
To retrieve file names, you can use System.IO:
string[] filePaths = Directory.GetFiles(path, "*.txt")
The Directory class is in System.IO.
I doubth that your folder name is correct. I'll recommend you use storeFile.GetDirectoryNames("*") to see what the correct paths for the directory is.
Microsoft wrote a great example I think you should try and take a look at, since there's nothing obvious wrong with your code.