delete a folder and its content - c#

I just followed this tutorial to delete a folder and its content
public ActionResult Product_Delete()
{
string idnumber = "07";
string path1 = #"~/Content/Essential_Folder/attachments_AR/" + idnumber;
DirectoryInfo attachments_AR = new DirectoryInfo(Server.MapPath(path1));
EmptyFolder(attachments_AR);
Directory.Delete(path1);
....
}
private void EmptyFolder(DirectoryInfo directory)
{
foreach (FileInfo file in directory.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo subdirectory in directory.GetDirectories())
{
EmptyFolder(subdirectory);
subdirectory.Delete();
}
}
But using this its deleting all the contnet in 07 folder, but its not deleting the 07 folder finally.
I'm getting error in this line Directory.Delete(path1);
Once I debug I can see run time error with below message
Could not find a part of the path 'C:\Program Files (x86)\IIS
Express\~\Content\Essential_Folder\attachments_AR\07'.
but path1 value is ~/Content/Essential_Folder/attachments_AR/07

The reason is that Directory.Delete cannot recognize ~ in the path.
You need to convert it to an absolute path using Server.MapPath() like you did it here:
DirectoryInfo attachments_AR = new DirectoryInfo(Server.MapPath(path1));
You may also want to convert it once, and use in both methods:
public ActionResult Product_Delete()
{
string idnumber = "07";
string mappedPath1 = Server.MapPath(#"~/Content/Essential_Folder/attachments_AR/" + idnumber);
DirectoryInfo attachments_AR = new DirectoryInfo(mappedPath1));
EmptyFolder(attachments_AR);
Directory.Delete(mappedPath1);
....
}
By the way, there is absolutely no need to remove files manually. You can use
public ActionResult Product_Delete()
{
string idnumber = "07";
string mappedPath = Server.MapPath(#"~/Content/Essential_Folder/attachments_AR/" + idnumber);
Directory.Delete(mappedPath, true);
}
which will remove all folders, subfolders and files recursively, and then will remove directory itself.

you cannot delete a directory by giving its physical path. from a web application using Directory.Delete(), so you have to convert it into absolute path by using Server.MapPath()
Use : Directory.Delete(Server.MapPath(path1));
Or you can use Like the following without using EmptyFolder() method :
DirectoryInfo dir = new DirectoryInfo(Server.MapPath(path1));
dir.GetFiles("*", SearchOption.AllDirectories).ToList().ForEach(file=>file.Delete());
// will delete all files in the folder and its sub folder
//so you don't need to iterate each sub folder and files in it
Directory.Delete(Server.MapPath(path1));

you should delete the directly using full path instead of relative path. Try with
Directory.Delete(attachments_AR.FullName);

Just take separate path of the folder in variable and pass this variable in Directory.Delete(.) Like :
var path = Server.MapPath(#"~/Test");
DirectoryInfo attachments_AR = new DirectoryInfo(path);
Directory.Delete(path);

Why don't you use method from Directory class (MSDN documentation):
public static void Delete(
string path,
bool recursive
)
Your code will be cleaner and simplier but much more important is that when building path manually you can achive path long limit. I get issue like this and solution was use this method.

Here is a solution what I did and it is deleting the root folder too:
public ActionResult Product_Delete()
{
string idnumber = "07";
string path1 = #"~/Content/Essential_Folder/attachments_AR/" + idnumber;
DirectoryInfo attachments_AR = new DirectoryInfo(Server.MapPath(path1));
EmptyFolder(attachments_AR);
if (attachments_AR.Exists && IsDirectoryEmpty(attachments_AR.FullName))
attachments_AR.Delete();
}
private static void EmptyFolder(DirectoryInfo directory)
{
foreach (FileInfo file in directory.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo subdirectory in directory.GetDirectories())
{
EmptyFolder(subdirectory);
subdirectory.Delete();
}
}
public static bool IsDirectoryEmpty(string path)
{
return !Directory.EnumerateFileSystemEntries(path).Any();
}

Related

How to get approximate file path?

I have a list file path as follow:
C:\Data\Default.aspx
C:\Data\Global.asax
C:\Data\Web.config
C:\Data\bin\PerlsComWebProject1.dll
C:\Data\bin\PerlsComWebProject1.pdb
I have a method to get file from folder path, however I want to print result as below:
Data\Default
Data\Global
Data\Web.config
Data\bin\PerlsComWebProject1
Data\bin\PerlsComWebProject1
Call: GetFilePathWithOutExtention(#"C:\\Data");
My code is only return file without an extension.
void GetFilePathWithOutExtention(string path)
{
string[] paths = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
foreach(var path in paths)
{
Console.WriteLine(Path.GetFileNameWithoutExtension(path));
}
}
Update: Thanks for your comments. "C:\Data\" is only a sample, sorry so make you confused. Actual, I have a any folder, I want to search this folder, get approximate path: this folder...\filename with out extention.
Ex: I have a path as follow: D:\EHO\Phase1\Data\Document\text.txt,....when I call method: GetFilePathWithOutExtention("D:\EHO\Phase1"), I want to output: Phase1\Data\Document\text, or GetFilePathWithOutExtention("D:\EHO\Phase1\Data"), output: Data\Document\text.
Thanks.
I think what you're looking for is Uri.MakeRelativeUri
So you could do something like this:
var folder = new Uri(#"C:\Data");
var paths = System.IO.Directory.GetFiles(folder.LocalPath, "*.*", System.IO.SearchOption.AllDirectories);
foreach (var uri in paths.Select(p => new Uri(p)))
{
Console.WriteLine(folder.MakeRelativeUri(uri).ToString());
}
This prints
Data/Default.aspx
Data/Global.asax
Data/Web.config
Data/bin/PerlsComWebProject1.dll
Data/bin/PerlsComWebProject1.pdb
A generic answer, valid for all folders inside the machine drives, not only 1st level:
void GetFilePathWithOutExtention(string path)
{
// Get the name of the folder containing your path (for further remove in the items folder)
string parentFolderName = Directory.GetParent(path).FullName;
string[] filePaths = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
foreach(string fileItemPath in filePaths)
{
// Get the current folder without the initial folder path
string currentItemPath = Path.GetDirectoryName(fileItemPath).Remove(0, parentFolderName.Length);
Console.WriteLine(Path.Combine(currentItemPath, Path.GetFileNameWithoutExtension(fileItemPath)));
}
}
you can just Show from the 4th char
void GetFilePathWithOutExtention(string path)
{
string[] filesName = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
foreach(var fileName in filesName)
{
string pathToWrite = Path.GetFileNameWithoutExtension(fileName);
if(pathToWrite != null && pathToWrite.length >3 )
Console.WriteLine(pathToWrite.Substring(3,pathToWrite.length);
}
}

Can't add files to listbox...READ

I'm using a code to show all startup items in listbox with environment variable "%appdata%
There is some errors in this code that I need help with....
Check code for commented errors
Is there any other solution but still using %appdata%?
This is the code:
private void readfiles()
{
String startfolder = Environment.ExpandEnvironmentVariables("%appdata%") + "\\Microsoft\\Windows\\Start Menu\\Programs\\Startup";
foldertoread(startfolder);
}
private void foldertoread(string folderName)
{
FileInfo[] Files = folderName.GetFiles("*.txt"); // HERE is one error "Getfiles"
foreach (var file in Directory.GetFiles(folderName))
{
startupinfo.Items.Add(file.Name); // here is another error "Name"
}
}
This line won't work because folderName is a string (and does not have a GetFiles method):
FileInfo[] Files = folderName.GetFiles("*.txt");
The second error is occurring because the file variable is a string containing the filename. You don't need to call file.Name, just try the following:
startupinfo.Items.Add(file);
I don't think you need the following line:
FileInfo[] Files = folderName.GetFiles("*.txt");
The foreach loop will generate what you need.
Secondly, the file variable is a string, so rather than calling:
startupinfo.Items.Add(file.Name);
...call instead:
startupinfo.Items.Add(file);
Finally, instead of a var type for your loop, you can use a string, and you can specify the file type filter:
foreach (string fileName in Directory.GetFiles(folderName, "*.txt"))
The string object doesn't have a GetFiles() method. Try this:
string startfolder = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
string[] files = Directory.GetFiles(startfolder, "*.txt");
foreach (string file in files)
{
startupinfo.Items.Add(Path.GetFileNameWithoutExtension(file));
}
Path.GetFileNameWithoutExtension(file) returns just the file name instead of full path.

Directory is not reading properly

I am having One Directory
C:\Kuldeep\kverma\kver\
After that It consists thousands of Folders with Different name .Each Folder consists Different Excel File . I need to read Each Files from Different Folders .
I want To read All The Folders Path from C:\Kuldeep\kverma\kver\ Folder.
I used below code for getting the folders name with path ..
string path = #"C:\Kuldeep\kverma\kver\";
DirectoryInfo dir = new DirectoryInfo(path);
Console.WriteLine("File Name Size Creation Date and Time");
Console.WriteLine("========");
foreach (DirectoryInfo dirinfo in dir.GetDirectories())
{
String name = dirinfo.Name;
String pth = dirinfo.FullName;
Console.WriteLine( name, pth);
}
Total 10700 folders are there in C:\Kuldeep\kverma\kver\ Directory But It is reading only 54 Folder..
Please provide me any solution for Reading Folder name and location Also Reading File from Each Folder in Single Shot .
You should put a try catch around the GetDirectories call to handle the exceptions in the below post.
That might give you a clue as to why it is not enumerating properly.
http://msdn.microsoft.com/en-us/library/c1sez4sc.aspx
Try a recursive approach:
namespace ConsoleApplication1
{
using System;
using System.Collections.Generic;
using System.IO;
class Program
{
public static IList<DirectoryInfo> dirs;
static void Main(string[] args)
{
dirs = new List<DirectoryInfo>();
var dir = new DirectoryInfo(#"c:\tmp");
GetDirs(dir);
Console.WriteLine(dirs.Count);
}
public static void GetDirs(DirectoryInfo root)
{
foreach (var directoryInfo in root.GetDirectories())
{
dirs.Add(directoryInfo);
GetDirs(directoryInfo);
}
}
}
}
Now I'm not sure what hidden dangers might be lurking because of this (Stack overflow exceptions, access denied?) so I'd recommend placing a try..catch block in the foreach loop to help you out.
If you want to view the contents of every sub directory:
// Flatten out the directory structure in to a string array.
var directoryList = Directory.GetDirectories("<<RootPath>>", "*", SearchOption.AllDirectories);
foreach (var directory in directoryList)
{
DirectoryInfo info = new DirectoryInfo(directory);
}
edited with the questions code updated:
string path = #"C:\Kuldeep\kverma\kver\";
string[] directoryArray = Directory.GetDirectories(path, "*", SearchOption.AllDirectories);
foreach (var directory in directoryArray)
{
DirectoryInfo dirinfo = new DirectoryInfo(directory);
String name = dirinfo.Name;
String pth = dirinfo.FullName;
Console.WriteLine(name, pth);
}

Efficient way to get the file list and copy to local directory?

I was trying to get the list of files in my remote directory and check only the file has name "test"; then copy to my local directory.
Just did a simple thing here but can someone please let me know the best way to handle this scenario.
class Program
{
static void Main(string[] args)
{
var getfiles = new fileshare.Program();
string[] filteredfiles =getfiles.GetFileList();
bool b;
foreach (string file in filteredfiles)
{
if(b=file.Contains("test"))
{
getfiles.copytolocal(file);
}
}
}
private string[] GetFileList()
{
string[] filepaths = Directory.GetFiles(#"\\testserver\dev");
return filepaths;
}
private void copytolocal(string filename)
{
File.Copy(filename, #"C:\" + filename);
}
}
Even i just stuck up when i was copy the file,the filename contains the whole directory inside the filename so filename look like "\\testserver\dev\test.txt". So it failed to copy in to local.
You can use DirectoryInfo to filter down to any file that contains the string "test":
private FileInfo[] GetFileList(string pattern)
{
var di = new DirectoryInfo(#"\\testserver\dev");
return di.GetFiles(pattern);
}
and then:
foreach (var file in GetFileList("*test*"))
{
getfiles.copytolocal(file.FullName);
}
You're looking for Path.GetFileName() (which returns a string).

How do I create a file AND any folders, if the folders don't exist?

Imagine I wish to create (or overwrite) the following file :- C:\Temp\Bar\Foo\Test.txt
Using the File.Create(..) method, this can do it.
BUT, if I don't have either one of the following folders (from that example path, above)
Temp
Bar
Foo
then I get an DirectoryNotFoundException thrown.
So .. given a path, how can we recursively create all the folders necessary to create the file .. for that path? If Temp or Bar folders exists, but Foo doesn't... then that is created also.
For simplicity, lets assume there's no Security concerns -- all permissions are fine, etc.
To summarize what has been commented in other answers:
//path = #"C:\Temp\Bar\Foo\Test.txt";
Directory.CreateDirectory(Path.GetDirectoryName(path));
Directory.CreateDirectory will create the directories recursively and if the directory already exist it will return without an error.
If there happened to be a file Foo at C:\Temp\Bar\Foo an exception will be thrown.
DirectoryInfo di = Directory.CreateDirectory(path);
Console.WriteLine("The directory was created successfully at {0}.",
Directory.GetCreationTime(path));
See this MSDN page.
Use Directory.CreateDirectory before you create the file. It creates the folder recursively for you.
. given a path, how can we recursively create all the folders necessary to create the file .. for that path
Creates all directories and subdirectories as specified by path.
Directory.CreateDirectory(path);
then you may create a file.
You will need to check both parts of the path (directory and filename) and create each if it does not exist.
Use File.Exists and Directory.Exists to find out whether they exist. Directory.CreateDirectory will create the whole path for you, so you only ever need to call that once if the directory does not exist, then simply create the file.
You should use Directory.CreateDirectory.
http://msdn.microsoft.com/en-us/library/54a0at6s.aspx
Assuming that your assembly/exe has FileIO permission is itself, well is not right. Your application may not run with admin rights. Its important to consider Code Access Security and requesting permissions
Sample code:
FileIOPermission f2 = new FileIOPermission(FileIOPermissionAccess.Read, "C:\\test_r");
f2.AddPathList(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, "C:\\example\\out.txt");
try
{
f2.Demand();
}
catch (SecurityException s)
{
Console.WriteLine(s.Message);
}
Understanding .NET Code Access Security
Is “Code Access Security” of any real world use?
You want Directory.CreateDirectory()
Here is a class I use (converted to C#) that if you pass it a source directory and a destination it will copy all of the files and sub-folders of that directory to your destination:
using System.IO;
public class copyTemplateFiles
{
public static bool Copy(string Source, string destination)
{
try {
string[] Files = null;
if (destination[destination.Length - 1] != Path.DirectorySeparatorChar) {
destination += Path.DirectorySeparatorChar;
}
if (!Directory.Exists(destination)) {
Directory.CreateDirectory(destination);
}
Files = Directory.GetFileSystemEntries(Source);
foreach (string Element in Files) {
// Sub directories
if (Directory.Exists(Element)) {
copyDirectory(Element, destination + Path.GetFileName(Element));
} else {
// Files in directory
File.Copy(Element, destination + Path.GetFileName(Element), true);
}
}
} catch (Exception ex) {
return false;
}
return true;
}
private static void copyDirectory(string Source, string destination)
{
string[] Files = null;
if (destination[destination.Length - 1] != Path.DirectorySeparatorChar) {
destination += Path.DirectorySeparatorChar;
}
if (!Directory.Exists(destination)) {
Directory.CreateDirectory(destination);
}
Files = Directory.GetFileSystemEntries(Source);
foreach (string Element in Files) {
// Sub directories
if (Directory.Exists(Element)) {
copyDirectory(Element, destination + Path.GetFileName(Element));
} else {
// Files in directory
File.Copy(Element, destination + Path.GetFileName(Element), true);
}
}
}
}
Following code will create directories (if not exists) & then copy files.
// using System.IO;
// for ex. if you want to copy files from D:\A\ to D:\B\
foreach (var f in Directory.GetFiles(#"D:\A\", "*.*", SearchOption.AllDirectories))
{
var fi = new FileInfo(f);
var di = new DirectoryInfo(fi.DirectoryName);
// you can filter files here
if (fi.Name.Contains("FILTER")
{
if (!Directory.Exists(di.FullName.Replace("A", "B"))
{
Directory.CreateDirectory(di.FullName.Replace("A", "B"));
File.Copy(fi.FullName, fi.FullName.Replace("A", "B"));
}
}
}

Categories