C# Extract the most recent zipped file only - c#

Finally got my code working fine, but I need to extract the most recent zipped file within the directory.
Really not sure how to go about this, can someone please point me in the correct direction, was thinking of using modified date and time, please see my code below...
using System;
using System.IO;
using System.IO.Compression;
namespace unZipMe
{
class Program
{
static void Main(string[] args)
{
DirectoryInfo file = new DirectoryInfo(#"c:\Temp\ZipSampleExtract");
if(file.Exists)
{
file.Delete(true);
}
string myDir = (#"c:\Temp\ZipSampleExtract");
bool exists = System.IO.Directory.Exists(myDir);
if (!exists)
{
System.IO.Directory.CreateDirectory(myDir);
}
//provide the folder to be zipped
//string folderToZip = #"c:\Temp\ZipSample";
//provide the path and name for the zip file to create
string zipFile = #"c:\Temp\ZipSampleOutput\MyZippedDocuments.zip";
//call the ZipFile.CreateFromDirectory() method
//ZipFile.CreateFromDirectory(folderToZip, zipFile, CompressionLevel.Optimal, false);
//specif the directory to which to extract the zip file
string extractFolder = #"c:\Temp\ZipSampleExtract\";
//call the ZipFile.ExtractToDirectory() method
ZipFile.ExtractToDirectory(zipFile, extractFolder);
}
}
}

Related

Can I maintain directory structure when zipping file?

I'm attempting to zip up a handful of files but these files could exist in different directories. The zipping portion is working correctly but I cannot figure out how to get it to preserve the directory structure within the zip file.
Here's what I have so far:
public static void CreateZipFile(IEnumerable<FileInfo> files, string archiveName)
{
using (var stream = File.OpenWrite(archiveName))
using (var archive = new ZipArchive(stream, ZipArchiveMode.Create))
{
foreach (var item in files)
{
archive.CreateEntryFromFile(item.FullName, item.Name, CompressionLevel.Optimal);
}
}
}
Is this possible?
#ErocM the link provided by #Flydog57 gives you exactly what you want. You are not exploiting the entryName argument correctly (the second argument in your case when calling CreateEntryFromFile).
Independently of which file you are adding to the archive (from same of different folders), you have to structure your archive using the entryName argument the C# api gives to you.
If your file's fullname is /tmp/myfile.txt, and you do archive.CreateEntryFromFile(item.FullName, item.Name), then the archive entry name will be myfile.txt. No folder created as the entry name doesn't contain folder structure in it's name.
However, if you call archive.CreateEntryFromFile(item.FullName, item.FullName), you will then have you file folder structure into the archive.
You can try with your function just changing item.Name into item.FullName.
Just be careful, on windows; if you path is C:\tmp\myfile.txt for instance, the archive will not be extractable correctly. You can then add some little code to remove C: from the full name of your files.
Some examples taking your implementation:
using System;
using System.IO;
using System.Collections.Generic;
using System.IO.Compression;
namespace ConsoleApp
{
internal class Program
{
static void Main(string[] args)
{
FileInfo f1 = new FileInfo(#"/tmp/test1.txt");
FileInfo f2 = new FileInfo(#"/tmp/testdir/test2.txt");
List<FileInfo> files = new();
files.Add(f1);
files.Add(f2);
CreateZipFile(files, #"/tmp/archive.zip");
}
public static void CreateZipFile(IEnumerable<FileInfo> files, string archiveName)
{
using (var stream = File.OpenWrite(archiveName))
using (var archive = new ZipArchive(stream, ZipArchiveMode.Create))
{
foreach (var item in files)
{
// Here for instance, I put all files in the input list in the same directory, without checking from where they are in the host file system.
archive.CreateEntryFromFile(item.FullName, $"mydir/{item.Name}", CompressionLevel.Optimal);
// Here, I am just using the actual full path of the file. Be careful on windows with the disk name prefix (C:, D:, etc...).
// archive.CreateEntryFromFile(item.FullName, item.FullName, CompressionLevel.Optimal);
}
}
}
}

How to copy and replace a file for all user profiles with Admin rights

I have researched all the articles here and on Google. While some seem to be what I need I continue to run into this problem. I could certainly use some assistance getting this resolved once and for all.
I want to copy a Customize.xml file from the server and have it replace the current file in all user profiles. I would prefer to make this so that it will run for anyone that logs on each time. Any assistance figuring this out and getting it to work would be greatly appreciated.
using System;
using System.Configuration;
using System.IO;
namespace copy_delete_move_files
{
public class SimpleFileCopy
{
public static object Logger { get; private set; }
static void Main()
{
string fileName = "Customize.xml";
string sourcePath = #"\\serverpath\c$\TestFolder";
string targetPath = #"\\desktoppath\c$\%USERPROFILE%\APPDATA\Roaming\Litera\Customize";
// Use Path class to manipulate file and directory paths.
string sourceFile = Path.Combine(sourcePath, fileName);
string destFile = Path.Combine(targetPath, fileName);
// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (!Directory.Exists(targetPath))
{
Directory.CreateDirectory(targetPath);
}
// To copy a file to another location and
// overwrite the destination file if it already exists.
File.Copy(sourceFile, destFile, true);
// To copy all the files in one directory to another directory.
// Get the files in the source folder.
// Note: Check for target path was performed previously
// in this code example.
if (Directory.Exists(sourcePath))
{
string[] files = 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 = Path.GetFileName(s);
destFile = Path.Combine(targetPath, fileName);
File.Copy(s, destFile, true);
}
}
else
{
Console.WriteLine("Source path does not exist!");
}
// Keep console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}

Copy files from listbox to another directory

I'm fairly new to C# and what I'm trying to do is
Search for a file
List all matching files into a listbox
Copy the whole folder where the file is located to another place
I found bits and pieces on the web that I'm using. Right now it's only the btn_search_Click part that is working.
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btn_search_Click(object sender, EventArgs e)
{
try
{
listBox1.Items.Clear();
//Directory to search in
DirectoryInfo Di = new DirectoryInfo(#"D:\xxxx\Versionen");
FileInfo[] nPfad = Di.GetFiles(textBox1.Text, SearchOption.AllDirectories);
Int32 nLengePfad = nPfad.GetLength(0);
listBox1.Items.AddRange(nPfad);
}
catch (Exception)
{
MessageBox.Show("File not found");
}
}
private void btn_save_Click(object sender, EventArgs e)
{
{
string sourceFile = #"D:\Users\Public\public\test.txt";
string destinationFile = #"D:\Users\Public\private\test.txt";
// To move a file or folder to a new location:
System.IO.File.Move(sourceFile, destinationFile);
// To move an entire directory. To programmatically modify or combine
// path strings, use the System.IO.Path class.
System.IO.Directory.Move(#"C:\Users\Public\public\test\", #"C:\Users\Public\private");
}
}
}
}
My question now is, what would the code look like, if I want to select a file from the listbox and copy NOT the file but the folder it's located in to another place. I already have set a btn_save and a basic code to move files, but I need someone to show me a way to copy any selected file from the listbox or rather copy the folder of the selected file.
I'm fairly new to C# and am open for new approaches. If I'm completely wrong with the code, scratch it, show me a correct or easier way to achieve the same
You can move directly the directory with Directory.Move.
Using the FileInfo.DirectoryName you can get the Directory path from the FileInfo[] SelectedItems.
var itemsToMove = myListBox.SelectedItems.Cast<FileInfo>();
var directoriesTheyAreIn = itemsToMove.Select(x => x.DirectoryName);
var cleanDirectoriesList = directoriesTheyAreIn.Distinct();
//As many file can be in the same Dir we only need to move the dire once to move those file.
But what if Dir contains both selected and unselected files? Here I will move them all.
foreach (var path in cleanDirectoriesList)
{
// here you have to craft your destination directory
string destinationDirectory = "";
Directory.Move(path, destinationDirectory);
}
From your question it's unclear what part of the old path should be keep in the new path. but if it's based on your "D:\xxxx\Versionen" string you can simply replace this part with the new root path "NewRoot\foo\bar":
string destinationDirectory = path.Replace(#"D:\xxxx\Versionen", #"G:\FooBAR\NEWPATH\");
If you need to move only the selected file you can blindly call Directory.CreateDirectory before copying each file, as it won't throw error if the directory already exist. Grouping on directory to avoid useless instruction could have been possible but I feel like it won't be that easy to modify. Here the code will simply be: create the directory then move the file.
foreach (var item in itemsToMove) {
string destinationDirectory = #"BasedPath\" + " Craft it ";
Directory.CreateDirectory(destinationDirectory);
File.Move(item.FullName, destinationDirectory + item.Name);
}
Store the list of files into a List<FileInfo> and iterate through with foreach. This worked for me:
string destination = #"C:\Some\Destination\";
string actualFile = string.Empty;
foreach (var file in fileList)
{
actualFile = file.FullName;
File.Copy(actualFile, destination + Path.GetFileName(actualFile));
}

Save image from URL to local hard drive using C#

Im trying to write a console application in order to store a single image from a given path into a new directory as suggested in this article. Despite my program not throwing out any errors the image I want to download just won't show up in my folder. I guess that's because I never told my program where I want the file to be saved? However, I haven't found anything clarifying this particular problem I have right now. I already referred to this and this question, too.
using System;
using System.IO;
using System.Net;
namespace GetImages
{
class Program
{
static void Main(string[] args)
{
string dirPath = #"C:\Users\Stefan\Desktop\Images";
try
{
// Create a new directory
DirectoryInfo imageDirectory = Directory.CreateDirectory(dirPath);
Console.WriteLine($"Directory '{Path.GetFileName(dirPath)}' was created successfully in {Directory.GetParent(dirPath)}");
// Image I'm trying to download from the web
string filePath = #"http://ilarge.lisimg.com/image/12056736/1080full-jessica-clements.jpg";
using (WebClient _wc = new WebClient())
{
_wc.DownloadFileAsync(new Uri(filePath), Path.GetFileName(filePath));
_wc.Dispose();
}
Console.WriteLine("\nFile successfully saved.");
}
catch(Exception e)
{
while (e != null)
{
Console.WriteLine(e.Message);
e = e.InnerException;
}
}
if (System.Diagnostics.Debugger.IsAttached)
{
Console.WriteLine("Press any key to continue . . .");
Console.ReadKey(true);
}
}
}
}
Edit: After some time I figured out that the file is saved in "C:\Users\Stefan\Documents\Visual Studio 2017\Projects\GetImages\GetImages\bin\Debug". But how do I get the file to be saved directly to dirPath without moving them from Debug to dirPath separately? My next step would be extending this program to save multiple files at once.
The second argument of DownloadFileAsync is the save location so combine the path you create and the filename from the URL:
_wc.DownloadFileAsync(new Uri(filePath), Path.Combine(dirPath, Path.GetFileName(filePath)));
Try this:
using (WebClient _wc = new WebClient())
{
_wc.DownloadFileAsync(new Uri(filePath), Path.Combine(dirPath,Path.GetFileName(filePath)));
}

C# Move Files From A Folder To Another (How to code: if doesn't exist do nothing)

Beginner: Here is my code:
using System;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
public void MoveFiles(string sourcePath, string destinationPath)
{
string[] files = Directory.GetFiles(sourcePath);
Parallel.ForEach(files, file =>
{
if ("HOW TO CODE: If the sourceFiles exist in destFolder")
{
File.Move(file, Path.Combine(destinationPath, Path.GetFileName(file)));
}
});
}
I get an error if the source files exist in destination folder. How can I correct that and is there a better way to do that?
File has the static methods Delete and Exists you can use for that very case
if(File.Exists(file))
{
if(File.Exists(destinationFile))
{
File.Delete(destinationFile);
}
File.Move(file, destinationFile);
}
I've used destinationFile to avoid redundancy.

Categories

Resources