Check Zip File content and extract - c#

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", "");
}

Related

Why is File.Move not working as expected?

I am trying to move all files from rootFolderPath to destinationPath
try
{
string rootFolderPath = #"D:\Log_siteq\";
if (!Directory.Exists(Path.Combine(#"D:\Log_takaya\" + comboBox1.SelectedItem.ToString())))
{
System.IO.Directory.CreateDirectory(Path.Combine(#"D:\Log_takaya\" + comboBox1.SelectedItem.ToString()));
}
string destinationPath = Path.Combine(#"D:\Log_takaya\" + comboBox1.SelectedItem.ToString() );
string fileTypes = #"*.*";
string[] fileList = System.IO.Directory.GetFiles(rootFolderPath, fileTypes);
foreach (string file in fileList)
{
string ext = Path.GetExtension(file);
string destination = Path.Combine(destinationPath,file);
File.Move( file,destination);
MessageBox.Show(file);
MessageBox.Show(destination);
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
Apparently MessageBox.Show(file); shows me my root folder path ( as is normal) but MessageBox.Show(destination); is showing me the same thing.
What gives? It just moves my file from my root folder in the same folder.Am I not getting something?
You are combining the destinationPath with the complete file path of file:
string destination = Path.Combine(destinationPath, file);
which will just overwrite the destination with the original file path (because "C:\desitnation\C:\source\filename.txt" isn't a valid path).
Instead, you need only the file name like this:
string destination = Path.Combine(destinationPath, Path.GetFileName(file));

How to replace an image with same name but different type of another image in a folder?

Suppose i have a folder and in this folder is an image named im1.png. i want that im1.png is deleted when i save another image named im1.jpg or im1.bmp or so on...(same name but different type) in this folder. i write following code but this code just delete file that has same name and same type. Help me please...
string CopyPic(string MySourcePath, string key, string imgNum)
{
string curpath;
string newpath;
curpath = Application.Current + #"\FaceDBIMG\" + key;
if (Directory.Exists(curpath) == false)
Directory.CreateDirectory(curpath);
newpath = curpath + "\\" + imgNum + MySourcePath.Substring(MySourcePath.LastIndexOf("."));
string[] similarFiles = Directory.GetFiles(curpath, imgNum + ".*").ToArray();
foreach (var similarFile in similarFiles)
File.Delete(similarFile);
File.Copy(MySourcePath, newpath);
return newpath;
}
Here is one way to do it:
string filename = ...; //e.g. c:\directory\filename.ext
//Get the directory where the file lives
string dir = Path.GetDirectoryName(filename);
//Get the filename without the extension to use it to search the directory for similar files
string filenameWithoutExtension = Path.GetFileNameWithoutExtension(filename);
//Search the directory for files with same name, but with any extension
//We use the Except method to remove the file it self form the search results
string[] similarFiles =
Directory.GetFiles(dir, filenameWithoutExtension + ".*")
.Except(
new []{filename},
//We should ignore the case when we remove the file itself
StringComparer.OrdinalIgnoreCase)
.ToArray();
//Delete these files
foreach(var similarFile in similarFiles)
File.Delete(similarFile);

Copying all files from source folder to destination folder renaming all the files while coping in asp.net c# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have to transfer images from "SourceFolder/Images" to the "DestinationFolder/Photos" in asp.net c#. All the images in the source folder should be copied to destination renaming the original image name with newly generated name. For example, if a file in source folder is mountain.jpg and while coping this image name to destination folder, it need to be renamed as Current DateTime followed by underscore and original filename (2016-05-20_mountain.jpg).
My code is as below:
string sourcePath = Server.MapPath("~/SourceFolder/Images");
string targetPath = Server.MapPath("~/DestinationFolder/Photos");
foreach (var srcPath in Directory.GetFiles(sourcePath))
{
File.Copy(srcPath, srcPath.Replace(sourcePath, targetPath), true);
}
Above code successfully copies all files to target path with same name as original name, but I want to rename each file to different name while transferring the file names to destination.
I have change your code as folowing :
string sourcePath = Server.MapPath("~/SourceFolder/Images");
string targetPath = Server.MapPath("~/DestinationFolder/Photos");
foreach (var srcPath in Directory.GetFiles(sourcePath))
{
FileInfo fileInfo = new FileInfo(srcPath);
string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + fileInfo.Name;
File.Copy(srcPath, srcPath.Replace(sourcePath, targetPath).Replace(fileInfo.Name, fileName), true);
}
or you can use also :
string sourcePath = Server.MapPath("~/SourceFolder/Images");
string targetPath = Server.MapPath("~/DestinationFolder/Photos");
foreach (var srcPath in Directory.GetFiles(sourcePath))
{
FileInfo fileInfo = new FileInfo(srcPath);
string fileName = string.Format("{0}_{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), fileInfo.Name);
File.Copy(srcPath, string.Format("{0}/{1}", targetPath, fileName), true);
}
you can change the DateTime format as you like.
static void CopytoDestination(string sourcePath,string sourcePath)
{
string fileName = "test.txt";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
// To copy a file to another location and
// overwrite the destination file if it already exists.
System.IO.File.Copy(sourceFile, destFile, true);
// To copy all the files in one directory to another directory.
// Get the files in the source folder. (To recursively iterate through
// all subfolders under the current directory, see
// "How to: Iterate Through a Directory Tree.")
// Note: Check for target path was performed previously
// in this code example.
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.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 = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.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();
}
protected void btnTransferFiles_Click(object sender, EventArgs e)
{
string sourcePath = Server.MapPath("~/SourceFolder/Images");
string targetPath = Server.MapPath("~/DestinationFolder/Photos");
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
string fileName = string.Empty;
string destFile = string.Empty;
// 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 = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + fileName);
System.IO.File.Copy(s, destFile, true);
}
}
}

Remove sub-path of File name and create file structure

I have following List<String> fileNames getting passed to my method,
I want to remove the sub-path from that and create the left out file structure
string subPath = "C:\\temp\\test"
List<string> filesIncoming = new List[]{#"C:\temp\test\a.txt", #"C:\temp\test\intest\a.txt"};
string outputDir = "C:\\temp3\\temp";
Output should be:
C:\\temp3\temp\a.txt
C:\\temp3\temp\intest\a.txt
This is what I am trying
foreach (var file in files)
{
var directory = Path.GetDirectoryName(file);
DirectoryInfo source = new DirectoryInfo(directory);
var fileName = Path.GetFileName(file);
var destDir = Path.Combine(destinatonFilePath, source.Name); //how do I remove sub-path from source.Name and combine the paths properly?
CreateDirectory(new DirectoryInfo(destDir));
File.Copy(file, Path.Combine(destDir, fileName), true);
}
I think you should use the old good string.Replace to remove the common base path from your incoming files and replace it with the common base path for the output files
string subPath = "C:\\temp\\test"
string outputDir = "C:\\temp3\\temp";
foreach (var file in files)
{
// Not sure how do you have named these two variables.
string newFilePath = file.Replace(subPath, outputDir);
Directory.CreateDirectory(Path.GetDirectoryName(newFilePath));
File.Copy(file, newFilePath, true);
}

How to create a same directory as source copying a file in c#

I am copying file from my server.map path to some folder in C:\ But When i am copying my file i want that it create the folder path same it is in server.map path with file to copy
Here is my code where i am copying file but it is not creating the same directory which i want.
public void CopyFiles()
{
string Filename = "PSK_20150318_1143342198885.jpg";
string sourcePath = Server.MapPath("~/UserFiles/Images/croppedAvatar/");
string targetPath = #"C:\MyCopyFIle\";
// Use Path class to manipulate file and directory paths.
string sourceFile = System.IO.Path.Combine(sourcePath,Filename);
string destFile = System.IO.Path.Combine(targetPath,Filename);
// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
// To copy a file to another location and
// overwrite the destination file if it already exists.
System.IO.File.Copy(sourceFile, destFile, true);
// To copy all the files in one directory to another directory.
// Get the files in the source folder. (To recursively iterate through
// all subfolders under the current directory, see
// "How to: Iterate Through a Directory Tree.")
// Note: Check for target path was performed previously
// in this code example.
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.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 = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath);
System.IO.File.Copy(s, destFile, true);
}
}
else
{
Debug.WriteLine("Source path does not exist!");
}
}
Now the source path contain /userfiles/images/croppedavatar directory in it when I am copying it in c:\MyCopyFile I want it create a folder structure like c:\MyCopyFile\UserFile\Images\CroppedAvatar
you have to check each file structure and create the same on destination and then copy file as
public void CopyFiles(string srcpath, List<string> sourcefiles, string destpath)
{
DirectoryInfo dsourceinfo = new DirectoryInfo(srcpath);
if (!Directory.Exists(destpath))
{
Directory.CreateDirectory(destpath);
}
DirectoryInfo dtargetinfo = new DirectoryInfo(destpath);
List<FileInfo> fileinfo = sourcefiles.Select(s => new FileInfo(s)).ToList();
foreach (var item in fileinfo)
{
string destNewPath = CreateDirectoryStructure(item.Directory.FullName, destpath) + "\\" + item.Name;
File.Copy(item.FullName, destNewPath);
}
}
public string CreateDirectoryStructure(string newPath, string destPath)
{
Queue<string> queue = new Queue<string>(newPath.Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries));
queue.Dequeue();
while (queue.Count>0)
{
string dirName = queue.Dequeue();
if(!new DirectoryInfo(destPath).GetDirectories().Any(a=>a.Name==dirName))
{
Directory.CreateDirectory(destPath + "\\" + dirName);
destPath += "\\" + dirName;
}
}
return destPath;
}
You can simply create a folder structure using FileInfo Class:
string path=#"c:/MyCopyFile/UserFile/Images/CroppedAvatar/";
FileInfo file = new FileInfo(path);
file.Directory.Create();
This will create a directory where you can copy what you want to.
You can change your code like following
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
Filename = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, Filename);
string path = #"C:/MyCopyFile/UserFiles/Images/croppedAvatar/";
FileInfo file = new FileInfo(path);
file.Directory.Create();
string folderStructurePath = #"C:/MyCopyFile/UserFiles/Images/croppedAvatar/" + Filename;
System.IO.File.Copy(sourceFile, folderStructurePath, true);
}
}

Categories

Resources