De
I have to copy folders and files from one network folder to other. There are some files which cannot be copied since it is named with special characters.
There are so many folders and sub-folders with 3 GB of data. To avoid this problem, I want to write a C# program which can copy all folders, sub-folders and files
with a log file(notepad). Log file which should note the non-copying file details and its path so that easy to trace them further. Can anybody please help me quickly
by providing a c# program or at-least a reference. A console or Win-form application, I am using Visual studio 2010 and Windows 7
copying like below
Copy form :- https://ap.sharepoint.a5-group.com/cm/Shared Documents/IRD/EA
To :- https://cr.sp.a5-group.com/sites/cm/Shared Documents/IRD/EA
here, try this:
Edit: my answer works for local Network Directories, I didn't mention, that you want to copy directiories from HTTPS, for that you have to use WebClient with Credentials
class DirectoryCopyExample
{
string pathFrom = "C:\\someFolder";
string pathTo = "D:\\otherFolder";
string LogText = string.Empty;
static void Main()
{
// Copy from the current directory, include subdirectories.
DirectoryCopy(pathFrom, pathTo, true);
}
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
try
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
catch(Exception)
{
//Write Files to Log whicht couldn't be copy
LogText += DateTime.Now.ToString() + ": " + file.FullName;
}
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
}
at the end you have to save the variable LogTex to the file, or whatever you need
source: http://msdn.microsoft.com/en-us/library/bb762914(v=vs.110).aspx
Related
I have a folder that contains many png images in my resources of my WPF application. I would like to add this folder to appdata/roaming. Since there are many images that are sorted in folders, I would prefer to add the whole folder. Is there any way to do this?
By the way, the folder is in a directory called Resources and all the pngs are build as resources in Visual Studio.
Here is my code example for your question:
public void MyCopy()
{
//1.You can use the following code to get the path appdata/roaming, and suppose you want to copy the files to NewImageFolder
string strTarget = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString() + "\\NewImageFolder\\";
if (!Directory.Exists(strTarget))
{
Directory.CreateDirectory(strTarget);
}
//2. Then you need to get the path of your the File to be copied
string strSource = AppDomain.CurrentDomain.BaseDirectory;
strSource = strSource.Substring(0, strSource.LastIndexOf("bin")) + "Resources\\Image";
//3.Copy the file
DirectoryInfo dir = new DirectoryInfo(strSource);
FileInfo[] files = dir.GetFiles();
string strFileName = null;
foreach (FileInfo file in files)
{
strFileName = strSource + "\\" + file.Name;
File.Copy(strFileName, System.IO.Path.Combine(strTarget, System.IO.Path.GetFileName(strFileName)));
}
}
I want to delete a zip folder if it is exists. I have below code.
string zippath = #"C:\Neenu\Downloads.zip";
ZipFile.CreateFromDirectory(#"" + TemporaryFolder, #"" + zippath);
Just before the above code I want to check if folder exists or not. If exists I want to delete folder.
I think you meant How to delete zip file and not a folder.
Here, this should be easy:
File.Delete(zippath);
For deleting inner files and directories :
System.IO.DirectoryInfo di = new DirectoryInfo(path);
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in di.GetDirectories())
{
dir.Delete(true);
}
Refer below codeI am keeping a copy of txt file and after that creating a new one
If you wish to delete file without vreating backup than jst use File.Delete(path of file)
if (File.Exists(file_path))
{
new_file_path = file_path.Replace(".txt", " created on " + File.GetLastWriteTime(file_path).ToString("dd-MM-yyyy hh-mm-ss tt") + ".txt");
File.Move(file_path, new_file_path);
File.Delete(file_path);
}
I want to copy and paste sub-folders of source folder ABC To destination folder. But it is not working. Here is my C# code, it work's fine but it copies the whole folder instead of only the sub-folders.
// string fileName = "test.txt";
string sourcePath = "D:\\Shraddha\\Demo_Web_App\\Source";
string targetPath = "D:\\Shraddha\\Demo_Web_App\\Destination";
// Use Path class to manipulate file and directory paths.
string sourceFile = System.IO.Path.Combine(sourcePath);
string destFile = System.IO.Path.Combine(targetPath);
// 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
{
Console.WriteLine("Source path does not exist!");
}
// Keep console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
Alright, here we go:
This doesn't really makes sense. If targetPath exists, create targetPath folder?
if (System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
You probably meant:
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
What you need to do first is, getting all directories to begin with:
var allDirectories = Directory.GetDirectories(targetPath, "*", SearchOption.AllDirectories);
then you can loop through allDirectories with foreach, find all files in each folder and copy the contents.
The following line cannot work like provided:
destFile = System.IO.Path.Combine(targetPath);
File.Copy expects a path to a file where you want to copy the content from "s", but you are providing only the destination folder. You have to include a filename in the Path.Combine method.
If you parse the path strings with the Path.GetFileName method for example, you can pass the result (only the filename without full source path) as an additional argument to Path.Combine to generate a valid destination path.
Additionally, like uteist already said, you have to get all subdirectories first, because in your code example, you're only copying the files, directly placed under your root source folder.
To keep the Directory structure
foreach (var dir in System.IO.Directory.GetDirectories(sourcePath))
{
var dirInfo = new System.IO.DirectoryInfo(dir);
System.IO.Directory.CreateDirectory(System.IO.Path.Combine(targetPath, dirInfo.Name));
foreach (var file in System.IO.Directory.GetFiles(dir))
{
var fileInfo = new System.IO.FileInfo(file);
fileInfo.CopyTo(System.IO.Path.Combine(targetPath, dirInfo.Name, fileInfo.Name));
}
};
guys. I've got a problem I can't solve:
I have a 2 folders I choose with folderBrowserDialog and tons of files in source directory I need to move to the target directory. But, I have only to move files with a specific extension like .txt or any other extension I can get from textbox.
So how can I do it?
First get all the files with specified extension using Directory.GetFiles() and then iterate through each files in the list and move them to target directory.
//Assume user types .txt into textbox
string fileExtension = "*" + textbox1.Text;
string[] txtFiles = Directory.GetFiles("Source Path", fileExtension);
foreach (var item in txtFiles)
{
File.Move(item, Path.Combine("Destination Directory", Path.GetFileName(item)));
}
Try this:
For copying files...
foreach (string s in files)
{
File.Copy(s, "C:\newFolder\newFilename.txt");
}
for moving files
foreach (string s in files)
{
File.Move(s, "C:\newFolder\newFilename.txt");
}
Example for Moving files to Directory:
string filepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
DirectoryInfo d = new DirectoryInfo(filepath);
foreach (var file in d.GetFiles("*.txt"))
{
Directory.Move(file.FullName, filepath + "\\TextFiles\\" + file.Name);
}
will Move all the files from Desktop to Directory "TextFiles".
Source and Target have the same subdirectories like this :
c:\fs\source\a\
c:\fs\source\b\
c:\fs\target\a\
c:\fs\target\b\
I am battling with copying files from source to target if not existing files. What is the best way in C# to compare source folders with target folders - check if target files dont exit, copy files from a specific source (c:\fs\source\a\config.xml and app.config) to a specific target (c:\fs\target\a\). If target files exist, ignore it. How to write it in C#?
Your code example very much appreciated. Thanks!
public void TargetFileCreate()
{
foreach (var folder in SourceFolders)
{
string[] _sourceFileEntries = Directory.GetFiles(folder);
foreach (var fileName in _sourceFileEntries)
{ //dont know how to implement here:
//how to compare source file to target file to check if files exist or not
//c:\fs\source\A\config.xml compares to c:\fs\target\A\ (no files) that should be pasted
//c:\fs\source\B\config.xml compares to c:\fs\target\B\config.xml that is already existed - no paste
}
}
}
foreach (var file in Directory.GetFiles(source))
{
File.Copy(file, Path.Combine(target, Path.GetFileName(file)), false);
}
You can check for each file if it exists this way:
string curFile = #"c:\temp\test.txt";
Console.WriteLine(File.Exists(curFile) ? "File exists." : "File does not exist.");
put this inside your loop. then copy those files there.
MSDN CODE:
// Simple synchronous file copy operations with no user interface.
// To run this sample, first create the following directories and files:
// C:\Users\Public\TestFolder
// C:\Users\Public\TestFolder\test.txt
// C:\Users\Public\TestFolder\SubDir\test.txt
public class SimpleFileCopy
{
static void Main()
{
string fileName = "test.txt";
string sourcePath = #"C:\Users\Public\TestFolder";
string targetPath = #"C:\Users\Public\TestFolder\SubDir";
// 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, 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();
}
}
foreach (var file in Directory.GetFiles(source))
{
var targetFile = System.IO.Path.Combine(target, System.IO.Path.GetFileName(file));
if(!File.Exists(targetFile))
{
File.Copy(file, targetFile)
}
}