Delete all files in a web directory - c#

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

Related

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 can delete folders in c sharp

I have some folders and these folders have some text files and i need delete these files but i catch an error with my code!
var dateFolder = Directory.GetDirectories(#"data\stdate").Select(Path.GetDirectoryName).ToArray();
foreach (var dateFile in dateFolder)
{
var stDates =
Directory.GetFiles(#"data\stdate\" + dateFile + "date").Select(Path.GetFileName).ToArray();
foreach (var date in stDates)
{
File.Delete(#"data\stdate\" + dateFile + "date\\" + date);
}
Directory.Delete(#"data\stdate\" + dateFile + "date");
}
try this:
Directory.Delete("Path", true); //true: It will delete directory by given path, also folders and files in it.
System.IO.DirectoryInfo di = new DirectoryInfo(#"data\stdate");
//This for delete all file in "data\stdate"
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
//***************************For delete file in folder
//This for delete all Subfolder and his files in "data\stdate"
foreach (DirectoryInfo dir in di.GetDirectories())
{
dir.Delete(true);
}
//*************************
//This for delete the parent folder "stdate"
di.Delete();
i delete my original folder and i create it again!
if (!isDateEmpty)
{
Directory.Delete(#"data\stdate", true);
Directory.CreateDirectory(#"data\stdate");
}
I suggest that you use system environment variables, see here:
https://en.wikipedia.org/wiki/Environment_variable
The reason being, like you found out: sometimes the executable is not running in the directory you expected when you compiled the program.
EX:
String query = "%SystemDrive%";
str = Environment.ExpandEnvironmentVariables(query);
Delete(str, true);
That way it guarantees a predictable path as opposed to a relative one.

Updating the files with new file

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

Read all files in directory sub folders

I have a folder - "C:\scripts"
Within "scripts" I have several sub folders e.g. - "C:\scripts\subfolder1" "C:\scripts\subfolder2" etc, that contain html files.
I am trying to use the following code -
foreach (string file in Directory.EnumerateFiles(#"C:\scripts","*.html"))
{
string contents = File.ReadAllText(file);
}
However this does not work due to the html files being in the sub folders.
How can I access the html files in the sub folders without having to manually put in the path of each sub folder?
use this overload from DirectoryInfo
var dir = new DirectoryInfo(#"c:\scripts");
foreach(var file in dir.EnumerateFiles("*.html",SearchOption.AllDirectories))
{
}
Directory.EnumerateFiles(#"C:\scripts","*.html",SearchOption.AllDirectories)
Seems to be the right solution for me try it :)
Maybe this works?
foreach (string file in Directory.GetFiles("C:\\Scripts\\", "*.html", SearchOption.AllDirectories))
{
string contents = File.ReadAllText(file);
}
From SearchOption.AllDirectories
Includes the current directory and all its subdirectories in a search
operation. This option includes reparse points such as mounted drives
and symbolic links in the search.
Try like this;
var d = new DirectoryInfo(#"c:\scripts");
foreach(var fin d.EnumerateFiles("*.html", SearchOption.AllDirectories))
{
}

Easiest way to check if file exists within a subfolder

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

Categories

Resources