Updating the files with new file - c#

I have 1,000 Uniquely named folders in one large folder.
Inside of each uniquely named folder these is another folder called /images.
Inside each image folder there is a file named "Read-Web-Site-Design-{UNIQUEFOLDERNAME}-ca-logo.png"
I want to replace the 1,768 .png files (while keeping the original name) from a .png file which I am supplying.
The folder structure and filenames need to remain same. Basically I'm updating the old file with a new file, using the same (unique) name, 1,000 times.
I have written this code and I am able to get all the files and directories in loop but I want to know how will I update files here,please check my code:
private List<String> DirSearch(string sDir)
{
List<String> files = new List<String>();
try
{
foreach (string f in Directory.GetFiles(sDir))
{
files.Add(f);
}
foreach (string d in Directory.GetDirectories(sDir))
{
files.AddRange(DirSearch(d));
}
}
catch (System.Exception excpt)
{
//MessageBox.Show(excpt.Message);
}
return files;
}

Simply you have to do a File.Copy() to replace old files with new .png file you are supplying.
Assuming you will have all the files to be replaced in the list,
List<String> files = new List<String>();
foreach (var file in files)
{
if (!string.IsNullOrWhiteSpace(file))
{
File.Copy("New File Path", "file to be replaced", true);
}
}
See, you are passing true as the 3rd parameter of the Copy() method, Which is to overrite if there is a file already in the destination path.
or you can use File.Replace(). Here you can keep the original file as a backup.
File.Replace("New File", "File to be replaced", "Back up of Original File");

You may wish to consider the following, It will handle the recursion for you, only find png files that have "Read-Web-Site" in their file path
foreach(var file in Directory.EnumerateFiles(dir, "*.png", SearchOption.AllDirectories)
.Where(x => x.Contains("Read-Web-Site")))
{
File.Copy(file, Path.Combine(new FileInfo(file).DirectoryName,"newName.png"), true);
}
If its another file you wish to overwrite to this file instead then its the same but
File.Copy("newFile", file, true);
Edit
Even better
foreach(var file in Directory.EnumerateFiles(dir,
"Read-Web-Site*.png",
SearchOption.AllDirectories))

Related

How can i check if a folder is empty with specific files types and then to delete the folder?

I want to delete each folder that have no gif images files inside.
i don't mind if it's having text files or any other files, if the folder/s have no gif files delete it.
var dirsRad = Directory.GetDirectories(radarImagesFolder);
var dirsSat = Directory.GetDirectories(satelliteImagesFolder);
if(dirsRad.Length > 0)
{
foreach(string dir in dirsRad)
{
if(!Directory.EnumerateFileSystemEntries(dir).Any())
{
Directory.Delete(dir, true);
}
}
}
if(dirsSat.Length > 0)
{
foreach (string dir in dirsSat)
{
if (!Directory.EnumerateFileSystemEntries(dir).Any())
{
Directory.Delete(dir, true);
}
}
}
The problem with this code is that if in the folder/s there is a text file it will not delete the folder/s , i want that even if there are any files that are not gif type delete the folder/s
Only if the folder/s contains gif images files then keep the folder/s.
Tried the code above but the folder/s some of them have a text file inside so it's not deleting the folder/s.
You can use this overload of the enumeration method you are using to only get files that end in .gif. If there aren't any, then delete the folder (including subdirectories and files).
This only applies to the current directory. If there are subdirectories of dirsRad with .gif files inside, they will be deleted. Exercise caution if that's not what you want.
It also assumes that a GIF file is simply identified by its lowercase extension. If you suspect you may have some GIF files that don't respect this, such as files written as .GIF, you'll have to make the method case-insensitive.
This translates to this simple change:
if(dirsRad.Length > 0)
{
foreach(string dir in dirsRad)
{
if(!Directory.EnumerateFileSystemEntries(dir, "*.gif").Any())
{
Directory.Delete(dir, true);
}
}
}

Delete Files containing specific Text in Directory and Subdirectories

How to delete Files there names containing a specific string in a Directory and also all Subdirectories?
Given Filenames like:
EA myown EURJPY M15 3015494.mq5
EA myown EURJPY M15 3015494.ex5
EA self EURJPY M15 3098111 fine.mq5
EA self EURJPY M15 3098111 fine.ex5
Given Folderstructures like:
D:\TEMP\MYTEST
D:\TEMP\MYTEST\EURJPY
D:\TEMP\MYTEST\EURJPY\EURJPY_M15
Example: I want to delete ALL Files in all Subdirectories containing this String:
3015494
These Files are copied more than one time down of the Root-Folder "D:\TEMP\MYTEST" and also copied into the Subdirectories.
I try to write a little function for this. But i can delete Files into a given Folder, but not down into Subfolders ...
Last Code from me:
// call my function to delete files ...
string mypath = #"D:\TEMP\MYTEST\";
string myfilecontains = #"xx";
DeleteFile(mypath, true, myfilecontains);
// some code i found here and should delete just Files,
// but only works in Root-Dir.
// Also will not respect my need for Filename contains Text
public static bool DeleteFile(string folderPath, bool recursive, string FilenameContains)
{
//Safety check for directory existence.
if (!Directory.Exists(folderPath))
return false;
foreach (string file in Directory.GetFiles(folderPath))
{
File.Delete(file);
}
//Iterate to sub directory only if required.
if (recursive)
{
foreach (string dir in Directory.GetDirectories(folderPath))
{
//DeleteFile(dir, recursive);
MessageBox.Show(dir);
}
}
//Delete the parent directory before leaving
//Directory.Delete(folderPath);
return true;
}
What i have to change in this Code for my needs?
Or is there a complete different code something more helpfull?
I hope you have some good ideas for me to catch the trick.
DirectoryInfo dir = new DirectoryInfo(mypath);
// get all the files in the directory.
// SearchOptions.AllDirectories gets all the files in subdirectories as well
FileInfo[] files = dir.GetFiles("*.*", SearchOption.AllDirectories);
foreach (FileInfo file in files)
{
if (file.Name.Contains(myfilecontains))
{
File.Delete(file.FullName);
}
}
This is similar to hossein's answer but in his answer if the directory name contains the value of myfilecontains that file will get deleted as well which I would think you don't want.
//get the list of files in the root directory and all its subdirectories:
string mypath = #"D:\TEMP\MYTEST\";
string myfilecontains = #"xx";
var files = Directory.GetFiles(mypath, "*", SearchOption.AllDirectories).ToList<string>();
//get the list of file for remove
var forDelete = files.Where(x => x.Contains(myfilecontains));
//remove files
forDelete.ForEach(x => { File.Delete(x); });
hope this helps!

how to find a file path of a particular file in program folder c#

I have a requirement to find the path of a particular file.
I know the file name and extension of the file. but i don't know where the file resides.
The file will in any of the sub directories of C:\Program Files. so i need to search inside the program folder for the file.
My file name is CASdb.accdb
One of the fastest ways is to enumerate over the files in the directory. Granted, in C:\Program Files there will be a lot of files, so you'd have to test this out to see how well it performs.
MSDN - Directory.EnumerateFiles Method
An example:
// LINQ query for all files containing the word 'Europe'.
var files = from file in
Directory.EnumerateFiles(#"C:\\Program Files\\", SearchOption.AllDirectories)
where file.ToLower().Contains("casdb.accdb")
select file;
You can use Environment.SpecialFolder.ProgramFiles to find files in ProgramFiles folder.
// Search All Files **Recursive**
DirSearch(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles));
files.Dump();
// Search Files in ProgramFiles Folder Only
files.AddRange(Directory.EnumerateFiles(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)));
files.AddRange(Directory.EnumerateFiles(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)));
static List<string> files = new List<string>();
static void DirSearch(string sDir)
{
try
{
foreach (string d in Directory.GetDirectories(sDir))
{
foreach (string f in Directory.GetFiles(d))
{
if (true /*logic*/)
files.Add(f);
}
DirSearch(d);
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}
you should implement search logic in foreach.

Delete all files in a web directory

I have a web directory that contains files and I want to delete them all. I've looked online but all the answers rely on the file system and I want to use the website's directories. I tried this:
foreach (string file in HttpContext.Current.Server.MapPath("\\MyDirectory"))
{
File.Delete(file);
}
The foreach statement is underlined and the error is 'cannot convert type char to string'.
What's the syntax to delete all files in a directory?
Your might need to correct your MapPath parameter (\\MyDirectory), but the syntax you need is shown below.
System.IO.DirectoryInfo di= new DirectoryInfo(HttpContext.Current.Server.MapPath("\\MyDirectory"));
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
Server.MapPath gives you a directory path, not an array of files/folders. IF you want to remove all files in the folder you would do this:
var folderPath = HttpContext.Current.Server.MapPath("\\MyDirectory");
foreach (string file in Directory.GetFiles(folderPath))
{
File.Delete(file);
}
If you wanted do delete the folder, then
var folderPath = HttpContext.Current.Server.MapPath("\\MyDirectory");
Directory.Delete(folderPath);
To delete all folders within the main folder
var folderPath = HttpContext.Current.Server.MapPath("\\MyDirectory");
foreach (string file in Directory.GetDirectoriesfolderPath))
{
File.Delete(file);
}

Copy Folders in C# using System.IO

I need to Copy folder C:\FromFolder to C:\ToFolder
Below is code that will CUT my FromFolder and then will create my ToFolder.
So my FromFolder will be gone and all the items will be in the newly created folder called ToFolder
System.IO.Directory.Move(#"C:\FromFolder ", #"C:\ToFolder");
But i just want to Copy the files in FromFolder to ToFolder.
For some reason there is no System.IO.Directory.Copy???
How this is done using a batch file - Very easy
xcopy C:\FromFolder C:\ToFolder
Regards
Etienne
This link provides a nice example.
http://msdn.microsoft.com/en-us/library/cc148994.aspx
Here is a snippet
// 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);
}
}
there is a file copy.
Recreate folder and copy all the files from original directory to the new one
example
static void Main(string[] args)
{
DirectoryInfo sourceDir = new DirectoryInfo("c:\\a");
DirectoryInfo destinationDir = new DirectoryInfo("c:\\b");
CopyDirectory(sourceDir, destinationDir);
}
static void CopyDirectory(DirectoryInfo source, DirectoryInfo destination)
{
if (!destination.Exists)
{
destination.Create();
}
// Copy all files.
FileInfo[] files = source.GetFiles();
foreach (FileInfo file in files)
{
file.CopyTo(Path.Combine(destination.FullName,
file.Name));
}
// Process subdirectories.
DirectoryInfo[] dirs = source.GetDirectories();
foreach (DirectoryInfo dir in dirs)
{
// Get destination directory.
string destinationDir = Path.Combine(destination.FullName, dir.Name);
// Call CopyDirectory() recursively.
CopyDirectory(dir, new DirectoryInfo(destinationDir));
}
}
Copying directories (correctly) is actually a rather complex task especially if you take into account advanced filesystem techniques like junctions and hard links. Your best bet is to use an API that supports it. If you aren't afraid of a little P/Invoke, SHFileOperation in shell32 is your best bet. Another alternative would be to use the Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory method in the Microsoft.VisualBasic assembly (even if you aren't using VB).
yes you are right.
http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.aspx
has provided copy function ..
or you can use another function
http://msdn.microsoft.com/en-us/library/ms127960.aspx
You'll need to create a new directory from scratch then loop through all the files in the source directory and copy them over.
string[] files = Directory.GetFiles(GlobalVariables.mstrReadsWellinPath);
foreach(string s in files)
{
fileName=Path.GetFileName(s);
destFile = Path.Combine(DestinationPath, fileName);
File.Copy(s, destFile);
}
I leave creating the destination directory to you :-)
You're right. There is no Directory.Copy method. It would be a very powerful method, but also a dangerous one, for the unsuspecting developer. Copying a folder can potentionaly be a very time consuming operation, while moving one (on the same drive) is not.
I guess Microsoft thought it would make sence to copy file by file, so you can then show some kind of progress information. You could iterate trough the files in a directory by creating an instance of DirectoryInfo and then calling GetFiles(). To also include subdirectories you can also call GetDirectories() and enumerate trough these with a recursive method.
A simple function that copies the entire contents of the source folder to the destination folder and creates the destination folder if it doesn't exist
class Utils
{
internal static void copy_dir(string source, string dest)
{
if (String.IsNullOrEmpty(source) || String.IsNullOrEmpty(dest)) return;
Directory.CreateDirectory(dest);
foreach (string fn in Directory.GetFiles(source))
{
File.Copy(fn, Path.Combine(dest, Path.GetFileName(fn)), true);
}
foreach (string dir_fn in Directory.GetDirectories(source))
{
copy_dir(dir_fn, Path.Combine(dest, Path.GetFileName(dir_fn)));
}
}
}
This article provides an alogirthm to copy recursively some folder and all its content
From the article :
Sadly there is no built-in function in System.IO that will copy a folder and its contents. Following is a simple recursive algorithm that copies a folder, its sub-folders and files, creating the destination folder if needed. For simplicity, there is no error handling; an exception will throw if anything goes wrong, such as null or invalid paths or if the destination files already exist.
Good luck!
My version of DirectoryInfo.CopyTo using extension.
public static class DirectoryInfoEx {
public static void CopyTo(this DirectoryInfo source, DirectoryInfo target) {
if (source.FullName.ToLower() == target.FullName.ToLower())
return;
if (!target.Exists)
target.Create();
foreach (FileInfo f in source.GetFiles()) {
FileInfo newFile = new FileInfo(Path.Combine(target.FullName, f.Name));
f.CopyTo(newFile.FullName, true);
}
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories()) {
DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name);
diSourceSubDir.CopyTo(nextTargetSubDir);
}
}
}
And use like that...
DirectoryInfo d = new DirectoryInfo("C:\Docs");
d.CopyTo(new DirectoryInfo("C:\New"));

Categories

Resources