ZipArchiveMode keep folder integrity - c#

I am trying to use the ZipArchiveMode to zip up a few files. The files are in different directories.
zipFile.CreateEntryFromFile(file, Path.GetFileName(file), compression);
I'm calling this for each file.
Is there a way to keep the folder integrity within the file so that it unzips in to the correct folder?
If not, do I have any other options for compressing files?
Thank you

Instead of just Path.GetFileName(file), use whatever portion of the fullname of the file is appropriate for your application. Something like this might work:
FileInfo fi = new FileInfo(file);
string path = fi.Directory.Parent + "\\" + fi.Name;

Related

moving file from one location to another without knowing file name

One of my executable process produces two files. I want to move one file that is produced to shared drive. I am writing an automatic process to move the file from one location to shared drive. The only issue is file name changes every time the executable is run so I don't have the exact filename with me. I only have the extension, .xls. I have only one .xls file in my directory.
I tried doing this
File.Copy(#"*.xls", #"\\serv44\Application\testing\name\test2\*.xls", true);
It threw an error saying Invalid name. After moving the file to shared drive. I want to delete the .xls file.
File.Delete("*.xls");
any help will be appreciated
You should get file name and then do whatever you want with that file. I.e. if you have only one xls file in the source directory:
var targetDirectory = #"\\serv44\Application\testing\name\test2\";
var sourceFile = Directory.EnumerateFiles(sourceDirectory, "*.xls").FirstOrDefault();
if (sourceFile != null)
{
var sourceFileName = Path.GetFileName(sourceFile);
var targetFileName = Path.Combine(targetDirectory, sourceFileName);
File.Copy(sourceFileName, targetFileName);
File.Delete(sourceFileName);
}
Note: instead of copy and delete you can use single Move operation.
If you want to move several files from your source directory, then instead of taking first one process all found files in a loop:
foreach(var sourceFile in Directory.EnumerateFiles(sourceDirectory, "*.xls"))
{
var sourceFileName = Path.GetFileName(sourceFile);
var targetFileName = Path.Combine(targetDirectory, sourceFileName);
File.Move(sourceFileName, targetFileName);
}
This should give you that file name:
var fileName = Directory.GetFiles(yourDirectory, "*.xls").ToList().FirstOrDefault();

Using GetCurrentDirectory as a path to save/create a file

I need to add a file name/file extension at the end of GetCurrentDirectory. I want to make the .txt file and write text to it
StreamWriter sw = new StreamWriter(Directory.GetCurrentDirectory, );
sw.WriteLine(a + ":Qwerty124");
sw.Close();
Is what i have so far. I want to make the file of the current directory + \example.txt
if the current directory is Sys32 it would look like this
C:\Windows\System32\example.txt
You can use the System.IO.Path.Combine method to append the file name at the end of the path. It essentially does a string append behind the scenes but it is smart enough to use the proper path separator and add it if necessary.
System.IO.Path.Combine(Directory.GetCurrentDirectory(), "example.txt");
Path.Combine
https://msdn.microsoft.com/en-us/library/fyy7a5kt(v=vs.110).aspx
Path.Combine(Directory.GetCurrentDirectory(), "example.txt")

Cannot create a file when it already exists using File.Move

I was trying to move a file from my Resx to my PC, but I'm keep having problems.
So I import a folder named "bad" in the Resources and I use the File.Move method to move the folder "bad" into my PC.
But the program keeps crashing because it says: Cannot create a file when its already exists.
Here the code I use:
//txtpath is the root folder. I let the user choose the root folder and save it in txtpath.text
private void btnbadname_Click(object sender, EventArgs e)
{
string source = "Resources\bad";
string destination = txtpath.Text + #"\RADS\projects\lol_air_client\releases\0.0.1.74\deploy\assets\locale\App";
File.Move(source, destination);
MessageBox.Show("脏话ID已开启, 教程请点击下面的链接");
}
The destination Directory cannot exist. In your code you are creating the Directory if it doesn't exist and then trying to move your directory, the Move Method will create the directory for you. If the Directory already exists you will need to Delete it or Move it.
See:
Cannot create a file when that file already exists when using Directory.Move
Destination supposed to have the filename as well
string destination = txtpath.Text + #"\RADS\projects\lol_air_client\releases\0.0.1.74\deploy\assets\locale\App\yourfilename.ext";
You are using File.Move to move directory, why not using Directory.Move.
The MSDN documentation will only move files from a source to a destination, while Directory.Move will move the directory itself.
If I misunderstood you, and you want to move a file;
You can check if the file exists before or not using something like:
if(File.Exists(fileName))
File.Delete(fileName);
Edit:
If you want to iterate through the directory and make sure that the file doesn't exist before moving it, you can use something like:
//Set the location of your directories
string sourceDirectory = #"";
string destDirectory = #"";
//Check if the directory exists, and if not create it
if (!Directory.Exists(destDirectory))
Directory.CreateDirectory(destDirectory);
DirectoryInfo sourceDirInfo = new DirectoryInfo(sourceDirectory);
//Iterate through directory and check the existance of each file
foreach (FileInfo sourceFileInfo in sourceDirInfo.GetFiles())
{
string fileName = sourceFileInfo.Name;
string destFile = Path.Combine(destDirectory, fileName);
if (File.Exists(destFile))
File.Delete(destFile);
//Finally move the file
File.Move(sourceFileInfo.FullName, destFile);
}
When using MoveTo, provide the full path of where you are sending the file, including the file name, eg, pic123.jpg. If you use DirectoryInfo to get an array of files and want to move any of them, append the Name property of the file to the directory path where you are sending the file.
imgFile.MoveTo("C:\myPictures\ArchiveFolder\pic123.jpg")

renaming file based on if it exists

I am currently dealing with an issue in iPads were when you upload an image via my site the image is renamed to "image.jpg" which is an issue as if it's in the same directory it can cause issues.. so I am trying to stop it renaming the file OR to add an incremental number onto the end of it, however I can't get this to function correctly.
I have used this small snippet of code to try and fix it, however it doesn't seem to work.
if(File.Exists(filename))
{
fileName = String.Format("{0}({1}", fileName, count++);
inputFile.PostedFile.SaveAs( String.Format( "{0}\\{1}", directory, fileName ) );
}
else
{
inputFile.PostedFile.SaveAs( String.Format( "{0}\\{1}", directory, fileName ) );
}
}
File.Exists(filename) expects complete file path to see if the file exists or not.
but in the line inputFile.PostedFile.SaveAs, you are concatenating filepath to be
directory + "//" + fileName.
so does your fileName actually consists of fullpath, or just the actual filename with extension?
if fileName consists of fullPath, inputFile.PostedFile.SaveAs should not work, as it would point to invalid location, and if fileName consists of just the file name and not complete path, then, File.Exists should not work. either way your logic is flawed.
I guess, now you know, what to change.
also, instead of using a counter, simply append DateTime.Now.ToString("hhmmddttmmss") to the fileName to make it unique.
When you call:
if(File.Exists(filename))
Make sure that filename includes the full path on disk to where you save the files.
From the looks of it you may want to use Path.Combine(directory, fileName) rather than just filename on its own.
You can generate the filename as
filename = filename + DateTime.Now.Ticks.ToString();
so that it will always be the new file. I mean it will retain the old as well as new file.
I hope it will help you.. :)
try this
fileName= Path.Combine(directory,fileName );
if(File.Exists(filename))
{
fileName = fileName + DateTime.Now.Ticks;
}
inputFile.PostedFile.SaveAs( fileName );

How to get files from ressources folder to copy them in an other directory in C#?

Hello I would like to know if it was possible to extract the files from the ressources folder to copy thme in a directory at the moment i've tried this :
protected void Form1_Load(object sender, EventArgs e)
{
FileInfo info = new FileInfo(file);
info.CopyTo(PATH + "\\shell" + "\\" + file, true);
Bitmap bmp = (Bitmap)Properties.Resources.ResourceManager.GetObject(file);
Image bitmap = Bitmap.FromFile(Environment.GetFolderPath (Environment.SpecialFolder.Desktop) + "ConnectableCORR\\ApplicationConnectTable\\Resources\\teapot.jpg");
bitmap.Save(Path.GetDirectoryName(PATH + "\\shell" + "\\" + "thumbnail_3D.png"), System.Drawing.Imaging.ImageFormat.Png);
}
But the copy isn't working am I doing anything wrong?
Best regards.
The method "Save" of object "Image" requires the name of file in "filename", and you are sending it:
Path.GetDirectoryName(PATH + "\\ shell" + "\\" + "thumbnail_3D.png")
Path.GetDirectoryName
Would return:
PATH + "\\ shell" + "\\"
Would fail the file name, you should also include the file name.
Edit
Try this and check the paths:
FileInfo info = new FileInfo(file);
MessageBox.Show(string.Format("File '{0}' exist '{1}'", info.FullName, info.Exists));
var destinationFile = string.Format("{0}\\shell\\{1}", PATH, file);
info.CopyTo(destinationFile, true);
MessageBox.Show(string.Format("File '{0}' exist '{1}'", destinationFile, File.Exists(destinationFile)));
I'm going to focus on the info.CopyTo() call, as that is the better way of your two options to copy the file. As it is written, there are a number of possibilities as to why it isn't working. For everything I'm thinking about, an exception would be thrown, so you should be able to add a try-catch block around your code and debug to see what the error is. Here's my best guesses, in the order I would try to debug them:
What is file? Is it a filename? Is it a full path plus filename? It looks to me like your code expects it to be fully-qualified in one place and just the name in another.
Source file doesn't exist. I would do a quick info.Exists to confirm that the file exists before trying to copy it.
Make sure the output filename makes sense. If file includes a path, then you really probably want to do info.CopyTo(PATH + "\\shell\\" + info.Name, true) unless you want to include the source path in the output path.
Output directory doesn't exist. If this is the case. A DirectoryNotFoundException will be thrown. Check if the directory exists and create it before doing your CopyTo.
Bad file name. Might contain invalid characters, which will cause either an ArgumentException or a NotSupportedException.
Path too long. Probably not this, but a PathTooLongException would be thrown.

Categories

Resources