I am going getting all the folders within a folder as follows:
foreach (DirectoryInfo directory in root.GetDirectories())
I now want to check all the files in each of those folder individualally for an XML file.If the XML file exists I want to do something.
What would be the best way to go about this?
I know this is the basis:
if (File.Exists("*.xml"))
{
}
but that is not working?
Try this method if you want to actually do something with the XML file. If you are just checking to see if any xml file exists then I would go a different route:
foreach (DirectoryInfo directory in root.GetDirectories())
{
foreach(string file in Directory.GetFiles(directory.FullName, "*.xml"))
{
//if you get in here then do something with the file
//an "if" statement is not necessary.
}
}
http://msdn.microsoft.com/en-us/library/wz42302f.aspx
The Directory.GetFiles method:
if (Directory.GetFiles(#"C:\","*.xml").Length > 0) {
// Do something
}
As an alternative you could use Directory.GetFiles with your search pattern and action upon the found files...
var existing = Directory.GetFiles(root, "*.xml", SearchOption.AllDirectories);
//...
foreach(string found in existing) {
//TODO: Action upon the file etc..
}
foreach (DirectoryInfo directory in root.GetDirectories())
{
// What you have here would call a static method on the File class that has no knowledge
// at all of your directory object, if you want to use this then give it a fully qualified path
// and ignore the directory calls altogether
//if (File.Exists("*.xml"))
FileInfo[] xmlFiles = directory.GetFiles("*.xml");
foreach (var file in xmlFiles)
{
// do whatever
}
}
Related
This should be very simple but I'm not sure what's wrong. I'm trying to delete all the files in a folder using File.Delete.
This is what I have so far:
DirectoryInfo ImageFolder = new DirectoryInfo(Program.FolderPath + #"\Images");
foreach (var File in ImageFolder.GetFiles())
{
File.Delete(File.FullName);
}
Then the ".Delete" becomes underlined and says no overload for method delete takes 1 argument.
Any help is appreciated.
What you're seeing is called Namespace Ambiguity.
In your own code or a reference DLL you probably have a method called Delete in a Class called File that doesn't support a single string parameter.
To fix the problem fully qualify File.Delete with System.IO, eg:
System.IO.File.Delete
To delete folder full of file use:
Directory.Delete(string directoryName, bool recursive);
https://msdn.microsoft.com/en-us/library/fxeahc5f(v=vs.110).aspx
Or from your code above, use:
DirectoryInfo ImageFolder = new DirectoryInfo(Program.FolderPath + #"\Images");
foreach (var fileInfo in ImageFolder.GetFiles())
{
fileInfo.Delete(); //this is FileInfo.Delete
// or
// File.Delete(fileInfo.FullName);
// dont use reserve "File" as your variable name
}
Remember, you are calling FileInfo, not File
You have to change the naming of the variable:
DirectoryInfo ImageFolder = new DirectoryInfo(Program.FolderPath + #"\Images");
foreach (var file in ImageFolder.GetFiles())
{
File.Delete(file.FullName);
}
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);
}
I have a list of directories - these folders are all websites - and I need to write some code to traverse down each one of these directories until I find the index.html file. When I find index.html, I need to write the entire path out to a text file. I know how to do basic file I/O, such as writing data to a file, but what I'm getting hung up on is how to traverse down each directory until I hit a certain file, then capture that entire path, then continue on to the next folder/directory. I'm not sure where to start and I was hoping I could find some guidance from you all.
There is a function that can do that : Directory.GetFiles Method (String, String, SearchOption)
Returns the names of files (including their paths) that match the specified search pattern in the specified directory, using a value to determine whether to search subdirectories.
If you just want to find the very first instance of a file with a particular name and stop searching immediately when you find it, this is the most efficient approach.
It uses the SearchOption.AllDirectories option to tell it to recursively descend the directories for you.
string rootPath = "X:\\MyRoot";
string targetPattern = "index.html";
string fullPath = Directory
.EnumerateFiles(rootPath, targetPattern, SearchOption.AllDirectories)
.FirstOrDefault();
if (fullPath != null)
Console.WriteLine("Found " + fullPath);
else
Console.WriteLine("Not found");
(Note that if you use Directory.GetFiles() it will iterate over all possible folders, even if it has already found an instance of the target file, whereas EnumerateFiles() allows you to stop iterating as soon as the file is found.)
This uses Linq's FirstOrDefault() to stop iterating as soon as a file is found, so you'll have to add using System.Linq;
Note that FirstOrDefault() will return null (for strings, as in this example) when there are no items in the sequence.
One important thing to be aware of is that both Directory.EnumerateFiles() and Directory.GetFiles() will throw exceptions if you attempt to access directories that you aren't allowed to (for example, if you start at the root of C:\, it could attempt to access C:\$Recycle.Bin which will cause an exception).
If you have many directories and files may enumerate them; it could be convenient if you want to exclude some directories:
public static String FindFileDeep(String path, String fileName) {
foreach(String file in Directory.EnumerateFiles(path))
if (String.Equals(Path.GetFileName(file), fileName, StringComparison.OrdinalIgnoreCase))
return file;
foreach (var dir in Directory.EnumerateDirectories(path)) {
// You can exclude some directories here:
// if (...) continue;
String result = FindIndexHtml(dir);
if (!String.IsNullOrEmpty(result))
return result;
}
return null;
}
...
String indexHtml = FindFileDeep(#"C:\MyFiles", "index.html");
Create a method that gets the contents of a directory (DirectoryInfo class) that is passed as a parameters.
Cycle through each of the .GetFiles() of the DirectoryInfo to find the flie.
Then, if need be, use the .GetDirectories() list and cycle through them re-calling the same function with the found directory name.
Disclaimer: Uncompiplied/untests - Prototype...
static void Main(string[] args)
{
FileInfo fi = FindFile("index.html", new DirectoryInfo("C:\\"));
}
static FileInfo FindFile(string Name, DirectoryInfo di)
{
FileInfo fiFound = null;
// Try and find it in this directory
FileInfo[] fiList = di.GetFiles("index.html");
if (fiList.Length == 0)
{
foreach (DirectoryInfo diCycle in di.GetDirectories())
{
fiFound = FindFile(Name, diCycle);
}
}
else
{
fiFound = fiList.First();
}
return (fiFound);
}
I want to delete a folder containing files and a subfolder, also containing files. I have used everything, but it is not working for me. I'm using the following function in my web-application asp.net:
var dir = new DirectoryInfo(folder_path);
dir.Delete(true);
Sometimes it deletes a folder, or sometimes it doesn't. If a subfolder contains a file, it only deletes the file, and not the folder as well.
Directory.Delete(folder_path, recursive: true);
would also get you the desired result and a lot easier to catch errors.
This looks about right: http://www.ceveni.com/2008/03/delete-files-in-folder-and-subfolders.html
//to call the below method
EmptyFolder(new DirectoryInfo(#"C:\your Path"))
using System.IO; // dont forget to use this header
//Method to delete all files in the folder and subfolders
private void EmptyFolder(DirectoryInfo directoryInfo)
{
foreach (FileInfo file in directoryInfo.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo subfolder in directoryInfo.GetDirectories())
{
EmptyFolder(subfolder);
}
}
The easiest way in my experience is this
Directory.Delete(folderPath, true);
But I am experiencing a problem with this function in a scenario when I am trying to create the same folder right after its deletion.
Directory.Delete(outDrawableFolder, true);
//Safety check, if folder did not exist create one
if (!Directory.Exists(outDrawableFolder))
{
Directory.CreateDirectory(outDrawableFolder);
}
Now when my code tries to create some file in the outDrwableFolder it ends up in exception. like for instance creating image file using api Image.Save(filename, format).
Somehow this piece of helper function works for me.
public static bool EraseDirectory(string folderPath, bool recursive)
{
//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))
{
EraseDirectory(dir, recursive);
}
}
//Delete the parent directory before leaving
Directory.Delete(folderPath);
return true;
}
You can also do the same by using the DirectoryInfo instance method. I just faced this problem and I believe this can resolve your problem too.
var fullfilepath = Server.MapPath(System.Web.Configuration.WebConfigurationManager.AppSettings["folderPath"]);
System.IO.DirectoryInfo deleteTheseFiles = new System.IO.DirectoryInfo(fullfilepath);
deleteTheseFiles.Delete(true);
For more details have a look at this link as it looks like the same.
I use the Visual Basic version because it allows you to use the standard dialogs.
https://msdn.microsoft.com/en-us/library/24t911bf(v=vs.100).aspx
Directory.Delete(path,recursive:true);
this code works for delete folder with N subfolder and files in it.
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"));