C# File.Move won't find existing file? - c#

I have a method that unzips files into an 'unzipped' files folder. Problem is that there are files duplicated in two zip files - so when the second zip file is extracted the process fails as the file name already exists. I decided to rename the existing file to avoid this problem, but my if(File.Exists...) statement is not picking up files that exist. This is probably a noob syntax issue?
private void UnzipFiles()
{
sourceDirectory = #"c:\id";
unzippedDirectory = #"C:\id\z_unzipped";
processedDirectory = #"C:\id\z_processed";
// get list of files from directory and unzip them
DirectoryInfo dirInfo = new DirectoryInfo(sourceDirectory);
FileInfo[] infos = dirInfo.GetFiles("*.zip");
foreach (FileInfo f in infos)
{
if (File.Exists(unzippedDirectory + #"\" + f.Name)){
// rename existing file
File.Move(unzippedDirectory + #"\" + f.Name, unzippedDirectory + #"\" + f.Name + " renamed by " + f.Name);
}
System.IO.Compression.ZipFile.ExtractToDirectory(f.FullName, unzippedDirectory);
File.Move(f.FullName, processedDirectory + #"\" + f.Name);
}
}

Related

Ionic.Zip package using C# ASP NET

I try to using the Ionic.Zip library for compress the pdf files stored in public folder on my server.
This is my structure on folder C:\inetpub\wwwroot\public\
Folder
1. C:\inetpub\wwwroot\public\ALABAMA
2. C:\inetpub\wwwroot\public\FLORIDA
3. C:\inetpub\wwwroot\public\CALIFORNIA
Subfolder
- C:\inetpub\wwwroot\public\ALABAMA\April
- C:\inetpub\wwwroot\public\ALABAMA\May
- C:\inetpub\wwwroot\public\FLORIDA\April
- C:\inetpub\wwwroot\public\FLORIDA\May
- C:\inetpub\wwwroot\public\CALIFORNIA\April
- C:\inetpub\wwwroot\public\CALIFORNIA\May
For each month subfolder I have stored the corresponding PDF file.
PDF Files
- C:\inetpub\wwwroot\public\ALABAMA\April\April_ALABAMA.pdf
- C:\inetpub\wwwroot\public\ALABAMA\May\May_ALABAMA.pdf
- C:\inetpub\wwwroot\public\FLORIDA\April\April_FLORIDA.pdf
- C:\inetpub\wwwroot\public\FLORIDA\May\May_FLORIDA.pdf
- C:\inetpub\wwwroot\public\CALIFORNIA\April\April_CALIFORNIA.pdf
- C:\inetpub\wwwroot\public\CALIFORNIA\May\May_CALIFORNIA.pdf
I need compress for each folder (ALABAMA, CALIFORNIA, CALIFORNIA) the pdf files stored in subfolder May month.
I need using Ionic.Zip library get these files
1. C:\inetpub\wwwroot\public\ALABAMA\May\May_ALABAMA.pdf
2. C:\inetpub\wwwroot\public\FLORIDA\May\May_FLORIDA.pdf
3. C:\inetpub\wwwroot\public\CALIFORNIA\May\May_CALIFORNIA.pdf
and compress these files into a single zip file named May_2022.zip saving on the folder
C:\inetpub\wwwroot\public\Zip\
The code below, instead, create three different zip files
- C:\inetpub\wwwroot\public\zip\ALABAMA_may_2022_06_17_16_24.zip
- C:\inetpub\wwwroot\public\zip\FLORIDA_may_2022_06_17_16_24.zip
- C:\inetpub\wwwroot\public\zip\CALIFORNIA_may_2022_06_17_16_24.zip
And if open the zip file, I've
C:\inetpub\wwwroot\public\zip\ALABAMA\ALABAMA_may_2022_06_17_16_24.zip
C:\inetpub\wwwroot\public\zip\FLORIDA\FLORIDA_may_2022_06_17_16_24.zip
C:\inetpub\wwwroot\public\zip\CALIFORNIA\CALIFORNIA_may_2022_06_17_16_24.zip
Instead of
ALABAMA_may_2022_06_17_16_24.zip
FLORIDA_may_2022_06_17_16_24.zip
CALIFORNIA_may_2022_06_17_16_24.zip
Any suggestion?
string zipPath, filename, prevMonthIn, root, folderName;
.....
try
{
string[] states = {
"ALABAMA",
"FLORIDA",
"CALIFORNIA" };
filename = #"C:\inetpub\wwwroot\public\";
foreach (string state in states)
{
prevMonthIn = DateTime.Now.AddMonths(-1).ToString("MMMM", CultureInfo.GetCultureInfo("en-US")) + "_" +
DateTime.Now.Year;
zipPath = #"C:\inetpub\wwwroot\public\zip\" +
state.ToString() + "_" +
prevMonthIn.ToString() + "_" +
DateTime.Now.ToString("MM_dd_HH_mm") + ".zip";
root = filename.ToString() + "/" + state.ToString() + "/" + prevMonthIn.ToString();
if (Directory.Exists(root))
{
using (ZipFile zipFile = new ZipFile())
{
foreach (var item in Directory.GetDirectories(root.ToString()))
{
folderName = new DirectoryInfo(item).Name;
zipFile.AddDirectory(item, folderName);
}
foreach (string file in Directory.GetFiles(root.ToString()))
{
zipFile.AddFile(file);
}
zipFile.Save(zipPath);
}
}
}
}
catch (Exception ex)
{
throw new ApplicationException("operation failed!", ex);
}
finally
{
}

Extract zip file and overwrite (in the same directory - C#)

I'm starting some C# stuff, and i would like to extract and force to overwrite all files from a zip archive. I know that there are many other solution in Stack, but nothing works for me :/
i've tried this method:
try
{
string zipPath = (Directory.GetCurrentDirectory() + "\\" + "my_zip");
Console.WriteLine("Zip's path: " + zipPath);
string extractPath = Directory.GetCurrentDirectory();
ZipFile.ExtractToDirectory(zipPath, extractPath);
return (0); // 0 all fine
}
catch (Exception)
{
return (1); // 1 = extract error
}
This extractor works fine, but doesn't allow me to overwrite files meanwhile extraction, and it returns error and exceptions ... i've tried to take a look at MS-Documention, without success ...
someone know how does it work ?
Try something like this. Away from my dev box so this may require some tweaking, just writing it from memory.
Edit: As someone mentioned you can use ExtractToFile which has an overwrite option. ExtractToDirectory does not.
Essentially you unzip to a temporary folder then check if an unzipped file's name already exists in the destination folder. If so, it deletes the existing file and moves the newly unzipped one to the destination folder.
try
{
string zipPath = (Directory.GetCurrentDirectory() + "\\" + "my_zip");
Console.WriteLine("Zip's path: " + zipPath);
//Declare a temporary path to unzip your files
string tempPath = Path.Combine(Directory.GetCurrentDirectory(), "tempUnzip");
string extractPath = Directory.GetCurrentDirectory();
ZipFile.ExtractToDirectory(zipPath, tempPath);
//build an array of the unzipped files
string[] files = Directory.GetFiles(tempPath);
foreach (string file in files)
{
FileInfo f = new FileInfo(file);
//Check if the file exists already, if so delete it and then move the new file to the extract folder
if (File.Exists(Path.Combine(extractPath,f.Name)))
{
File.Delete(Path.Combine(extractPath, f.Name));
File.Move(f.FullName, Path.Combine(extractPath, f.Name));
}
else
{
File.Move(f.FullName, Path.Combine(extractPath, f.Name));
}
}
//Delete the temporary directory.
Directory.Delete(tempPath);
return (0); // 0 all fine
}
catch (Exception)
{
return (1); // 1 = extract error
}
Edit, in the event directories are unzipped (again, may need to be tweaked, I didn't test it):
try
{
string zipPath = (Directory.GetCurrentDirectory() + "\\" + "my_zip");
Console.WriteLine("Zip's path: " + zipPath);
//Declare a temporary path to unzip your files
string tempPath = Path.Combine(Directory.GetCurrentDirectory(), "tempUnzip");
string extractPath = Directory.GetCurrentDirectory();
ZipFile.ExtractToDirectory(zipPath, tempPath);
//build an array of the unzipped directories:
string[] folders = Directory.GetDirectories(tempPath);
foreach (string folder in folders)
{
DirectoryInfo d = new DirectoryInfo(folder);
//If the directory doesn't already exist in the destination folder, move it to the destination.
if (!Directory.Exists(Path.Combine(extractPath,d.Name)))
{
Directory.Move(d.FullName, Path.Combine(extractPath, d.Name));
continue;
}
//If directory does exist, iterate through the files updating duplicates.
else
{
string[] subFiles = Directory.GetFiles(d.FullName);
foreach (string subFile in subFiles)
{
FileInfo f = new FileInfo(subFile);
//Check if the file exists already, if so delete it and then move the new file to the extract folder
if (File.Exists(Path.Combine(extractPath, d.Name, f.Name)))
{
File.Delete(Path.Combine(extractPath, d.Name, f.Name));
File.Move(f.FullName, Path.Combine(extractPath, d.Name, f.Name));
}
else
{
File.Move(f.FullName, Path.Combine(extractPath, d.Name, f.Name));
}
}
}
}
//build an array of the unzipped files in the parent directory
string[] files = Directory.GetFiles(tempPath);
foreach (string file in files)
{
FileInfo f = new FileInfo(file);
//Check if the file exists already, if so delete it and then move the new file to the extract folder
if (File.Exists(Path.Combine(extractPath,f.Name)))
{
File.Delete(Path.Combine(extractPath, f.Name));
File.Move(f.FullName, Path.Combine(extractPath, f.Name));
}
else
{
File.Move(f.FullName, Path.Combine(extractPath, f.Name));
}
}
Directory.Delete(tempPath);
return (0); // 0 all fine
}

Creating paths with variables (move a folder and contents to new folder)

looked all over and found plenty of stuff regarding this but none are using variables to form paths. What I need to do is move a folder, sub-folders and files to a new path on button click. So far none of what I found worked. At the moment, i'm getting no files or folders moved what so ever. The current solution I tried is from MSDN and tried to adapt it to my code. If you could correct the code and show me an example it would be great. I don't know what i'm doing wrong here. Here is the code:
private void CopyPartsToProject()
{
string sourcePath = (pathToQuotes + "/" + client_name.Text + "/" + quote_id.Text);
string targetPath = (pathToClient + "/" + client_name.Text + "/" + project_number.Text);
string sourceFile = sourcePath + "/" + "*.*";
string destinationFile = targetPath + "/" + "*.*";
System.IO.File.Move(sourceFile, destinationFile);
System.IO.Directory.Move(sourcePath, targetPath);
}
pathToQuotes and pathToClient are retreived from a MySQL database (from user input) in another method. The info is getting retreived without any problems and the paths are correct. If you could give me a hand it would be appreciated. Thanks.
You need a recursive method to achieve moving directories including all files and sub-directories:
private void moveDirectory(string sourcePath ,string targetPath)
{
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
String[] files = Directory.GetFiles(sourcePath);
String[] directories = Directory.GetDirectories(sourcePath);
foreach (string f in files)
{
System.IO.File.Copy(f, Path.Combine(targetPath,Path.GetFileName(f)), true);
}
foreach(string d in directories)
{
// recursive call
moveDirectory(Path.Combine(sourcePath, Path.GetFileName(d)), Path.Combine(targetPath, Path.GetFileName(d)));
}
}
then the usage is like this:
private void CopyPartsToProject()
{
string sourcePath = (pathToQuotes + "/" + client_name.Text + "/" + quote_id.Text);
string targetPath = (pathToClient + "/" + client_name.Text + "/" + project_number.Text);
moveDirectory(sourcePath, targetPath);
}

Check Zip File content and extract

Hi I want to extract a ZipFile that has various of text files. But i could be that de text files are in a folder. So what i want to do is: If an folder exists just exract normaly if not create a folder with name of ZipFile. The reason is i don't want to have a folder in a folder with the same name.
My Previous Code:
foreach (string file in newZips) {
FileInfo fileInfo = new FileInfo(file);
string dirName = newPath + "\\" + fileInfo.Name.Substring(0, fileInfo.Name.Length - 4);
Console.WriteLine(dirName);
Directory.CreateDirectory(dirName);
ZipFile.ExtractToDirectory(allZipsPath + "\\" + fileInfo.Name, dirName);
}
Maybe this helps you:
string path = #"C:\..\..\myFolder";
if(!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
Thats how you can check a path if it contains the Folder you expect. And if not it creates that Folder!
--- EDIT (if unknown zip-Name) ---
string myPathToZip = #"C:\..\..\folderName";
foreach (string file in Directory.GetFiles(myPathToZip, "*.zip", SearchOption.AllDirectories))
{
//the current path of the zipFile (with the Name included)
var path = new FileInfo(file.ToString());
//The filename
var filename = Path.GetFileName(file.ToString()).Replace(".zip", "");
}

File.Copy - DirectoryNotFoundException was unhandled

When I use this code it doesn't throw any errors but it still doesn't copy anything. Any ideas?.
//string spath = string.Format("S:\\ 0A36303 / user:admin");
DateTime theDate = dateTimePicker1.Value.Date;
DirectoryInfo Dir = new DirectoryInfo("S:");
string dircreate = string.Format(#"N:\{0:MM-dd-yyyy}\" + label1.Text + "LogFiles", dateTimePicker1.Value.Date, label1.Text);
DirectoryInfo target = new DirectoryInfo(dircreate);
FileInfo[] fis = Dir.GetFiles( ".txt", SearchOption.AllDirectories);
foreach (FileInfo fi in fis)
{
if (fi.LastWriteTime.Date == theDate)
{
File.Copy(fi.FullName, target.FullName + #"\" + fi.Name, true);
}
}
}
}
}
Try using the full UNC path to access the file:
DirectoryInfo Dir = new DirectoryInfo(#"\\server\\share\\pathtofile");
Two possible problems come to mind:
The S:\PC.log file doesn't exist => you cannot copy non-existent file
The process you are executing your code under doesn't have read permission to the specified folder (S:). Looks like a network share. If you are running this code inside an ASP.NET application the process probably doesn't have read permissions to this remote share => you cannot copy a file that you don't have permissions to access.

Categories

Resources