Copy and rename directory - c#

I'm trying to modify this code to copy and rename (instead of just move) multiple directories. I have a CSV file that has 2 columns. The "original folder name" and the "new folder name".
using System.Linq;
using System.IO;
string csv = "csv path";
string sourcedir = #"C:\temp1\";
string targetdir = #"C:\temp2\";
string[] items = File.ReadAllLines(csv);
foreach(var item in items)
{
string oldname = item.Split(';')[0];
string newname = item.Split(';')[1];
Directory.Move(sourcedir +oldname, targetdir +newname);
}

When source-folder doesn't contain nested folders then use this way:
string csv = "csv path";
string sourcedir = #"C:\temp1\";
string targetdir = #"C:\temp2\";
var items = File.ReadAllLines(csv);
foreach(var item in items)
{
var paths = item.Split(";");
var sourcePath = Path.Combine(sourcedir, paths[0]);
var targetPath = Path.Combine(targetdir, paths[1]);
System.IO.Directory.CreateDirectory(targetPath);
var files = System.IO.Directory.GetFiles(sourcePath);
foreach (string s in files)
{
var fileName = System.IO.Path.GetFileName(s);
var destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(s, destFile, true);
}
}
Otherwise, you need to use recursive traverse through nested folders - see example MS docs 'How to: Copy directories'.

Related

Copy files containing a name from source to destination c#

I have a list of Strings with a series of names, I want to find these names in the source directory and copy them to the destination.
This is what I am trying but with this I copy all source directory in target directory:
List<string> ncs = new List<string>();
ncs = getNames();
foreach (var file in Directory.GetFiles(sourceDir))
File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file)));
foreach (var directory in Directory.GetDirectories(sourceDir))
CopyNCfromTo(directory, Path.Combine(targetDir, Path.GetFileName(directory)));
I am trying in this way too:
List<string> ncs = new List<string>();
ncs = getNames();
for (int i = 0; i < ncs.Count; i++)
{
FileInfo[] filesInDir = hdDirectoryInWhichToSearch.GetFiles(ncs[i].ToString());
}
I thought to loop the list and the look for every file in the source folder, how could I do this?
I assume that the ncs list containing only names not the file path or the file name with extension.
foreach (var file in Directory.GetFiles(sourceDir))
if (ncs.Contains(Path.GetFileName(file).Split('.').First()))
File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file)));
This is happening because foreach is browsing the files contained in the folder and not the list of names, that way, all files are copied to the destination folder.
foreach(string fileName in ncs){
string path = sourceDir + fileName;
bool result = System.IO.File.Exists(path);
if(result == true){
string destinationPath = targetDir + fileName;
System.IO.File.Copy(path,destinationPath);
}
}
That way you go through the list of names and check if the file exists, if it exists, copy the file to the destination folder
You can iterate over ncs, build the source and destination paths, and do a copy if the file exists.
Caveat: File.Exists() can introduce a race condition. If you are not confident no other process is working in that folder then you should handle IO exceptions.
string sourceDir = "C:\\....";
string targetDir = "C:\\....";
foreach (string filename in ncs)
{
string srcFile = Path.Combine(sourceDir, filename);
string destFile = Path.Combine(targetDir, filename);
if (File.Exists(srcFile))
{
File.Copy(srcFile, destFile);
}
}

ASP.NET Windows Console Files + filename to ZIP

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

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

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