ASP.NET Windows Console Files + filename to ZIP - c#

I need to zip files from folder X to folder Y. When the files from folder X are zipped into folder Y. The files in folder X needs to be removed. The zip name must be the name of the file with the .DBS in that folder.
So I need to read whats the file name of the .DBS file is. Then I need to zip all the files in folder X to folder Y with the name: "Filename" (this is the same as the .DBS file) If the files are zipped and well in folder Y they need to be removed from folder X.
The code that I got at the moment will move the files of folder X too Y. So this is a start. My question is how can I get the name of the file too be the zip folder name.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.IO.Compression;
namespace Ramasoftzipper
{
class Program
{
static void Main(string[] args)
{
string fileName = #"160001.DBS";
string sourcePath = #"C:\RMExport";
string targetPath = #"C:\Exportrm";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
string startPath = #"C:\RMExport";
string zipPath = (fileName);
string extractPath = #"C:\Exportrm";
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
System.IO.File.Copy(sourceFile, destFile, true);
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
foreach (string s in files)
{
fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(s, destFile, true);
ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);
}
}
else
{
Console.WriteLine("Source path does not exist!");
}
}
}
}
Thanks in advance.

(only explaining this much because I know you and you need to learn this stuff, yo :P)
you could try something like this, read comments in code for more info, this code is only showing you how to zip all files in a folder, try the next step of adding certain extentions yourself
//files to zip, you can also use the same method as above to let the user determine what path to zip
string path = #"C:\Users\WsLocal.NL-ROE2-W297\Pictures";
string zipPath = #"C:\Users\WsLocal.NL-ROE2-W297\Desktop\zip\result.zip";
//zip files
ZipFile.CreateFromDirectory(path, zipPath);
string[] files = Directory.GetFiles(path);
//some debugging
foreach (string filePath in files)
{
Console.WriteLine(filePath);
}
//wait untill user presses enter
Console.ReadLine();
[EDIT]
setting the name of the zip file to a file name:
replace
string zipPath = #"C:\Users\WsLocal.NL-ROE2-W297\Desktop\zip\result.zip";
with
//get all files from directory decladed by path
string[] files = Directory.GetFiles(path);
//select the 1st one and delete the folder information so just the file name is left with it's extention
string zipName = files[0].Replace(path, "");
//delete the extention
int index = zipName.IndexOf(".");
if (index > 0)
zipName = zipName.Substring(0, index);
//assemble the zip location with the generated file name
string zipPath = #"C:\Users\WsLocal.NL-ROE2-W297\Desktop\zip\"+ zipName + ".zip";
and delete
string[] files = Directory.GetFiles(path);
under
//zip files
ZipFile.CreateFromDirectory(path, zipPath);

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));

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

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

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

copy all type format file from folder in c#

I am trying to copy all format file (.txt,.pdf,.doc ...) file from source folder to destination.
I have write code only for text file.
What should I do to copy all format files?
My code:
string fileName = "test.txt";
string sourcePath = #"E:\test222";
string targetPath = #"E:\TestFolder";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
Code to copy file:
System.IO.File.Copy(sourceFile, destFile, true);
Use Directory.GetFiles and loop the paths
string sourcePath = #"E:\test222";
string targetPath = #"E:\TestFolder";
foreach (var sourceFilePath in Directory.GetFiles(sourcePath))
{
string fileName = Path.GetFileName(sourceFilePath);
string destinationFilePath = Path.Combine(targetPath, fileName);
System.IO.File.Copy(sourceFilePath, destinationFilePath , true);
}
I kinda got the impression you wanted to filter by extension. If so, this will do it. Comment out the parts I indicate below if you don't.
string sourcePath = #"E:\test222";
string targetPath = #"E:\TestFolder";
var extensions = new[] {".txt", ".pdf", ".doc" }; // not sure if you really wanted to filter by extension or not, it kinda seemed like maybe you did. if not, comment this out
var files = (from file in Directory.EnumerateFiles(sourcePath)
where extensions.Contains(Path.GetExtension(file), StringComparer.InvariantCultureIgnoreCase) // comment this out if you don't want to filter extensions
select new
{
Source = file,
Destination = Path.Combine(targetPath, Path.GetFileName(file))
});
foreach(var file in files)
{
File.Copy(file.Source, file.Destination);
}
string[] filePaths = Directory.GetFiles(#"E:\test222\", "*", SearchOption.AllDirectories);
use this, and loop through all the files to copy into destination folder

Categories

Resources