Alright so I'm having a bit of an issue here. I'm trying to delete a specific folder inside another folder on my webserver using ASP.NET (C#) The folder being deleted is based on a textbox.
The directory is like this
/images/folderx
folderx = txtDelFolder.Text;
The problem is that everything I try deletes every single thing inside the images folder. I'm guessing that it is not recognizing my folder in the filepath
string path = #"\httpdocs\images\ +
txtDelFolder.Text;
I have also tried
string path = #"\httpdocs\images\ +
txtDelFolder.Text + "\";
Tried all this with both single '\' and double '\'
Would appreciate any help on this
Also where it says <directfilepath> I actually have the filepath typed out, just didn't want to share that here.
****edit****
string path = Server.MapPath("~/imagestest/" + txtEditTitle.Text);
if(Directory.Exists(path))
{
DeleteDirectory(path);
}
}
}
private void DeleteDirectory(string path)
{
foreach(string filename in Directory.GetFiles(path))
{
File.Delete(filename);
}
foreach(string subfolders in Directory.GetDirectories(path))
{
Directory.Delete(subfolders, true);
}
}
Try this:
private void DeleteFiles(string folder)
{
string path=Server.MapPath("~/httpdocs/images/" + folder);
string[] files=Directory.GetFiles(path, "*", SearchOption.AllDirectories);
foreach (string file in files)
{
File.Delete(file);
}
//then delete folder
Directory.Delete(path);
}
try this one :
public void DeleteFolder(string folderPath)
{
if (!Directory.Exists(folderPath))
return;
// get the directory with the specific name
DirectoryInfo dir = new DirectoryInfo(folderPath);
try
{
foreach (FileInfo fi in dir.GetFiles())
fi.Delete();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Don't see why this wouldn't work:
public static bool DeleteDirectory(string input)
{
if (Directory.Exists(input))
{
Directory.Delete(input, true);
return !Directory.Exists(input);
}
else
return true;
}
string thePath = Server.MapPath(#"~/images/");
thePath = Path.Combine(Path.GetFullPath(thePath), txtInput.Text);
if(DeleteDirectory(thePath))
Console.WriteLine("YAY");
else
Console.WriteLine("BOO");
Related
I have a situation where the user will enter the name of the file and at run-time (without specifying the path). And i must find out the file by c# code.
I have seen a function GetFullPath() but it just give the current directory path appended by fileName entered by user at run-time.
string fullPath;
Console.WriteLine("please enter teh name of the file to be searched");
String fileName = Console.ReadLine();
fullPath = Path.GetFullPath(fileName);
Is there any such way exist in c# to get full path of a file specified at run time ? (Without specifying about the path). I can convince the user for specifying the Drive (C:/D:/E:...) but for writing the full path at run time to find that file they will not agree.
EDIT: My try is this: (but it gives access denied) please help me if i am not smart enough to go to each directory and do not try to open the secured folder until i get my file.
public static string Search(string fileName)
{
string fullPath = string.Empty;
WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
WindowsPrincipal currentPrincipal = new WindowsPrincipal(currentIdentity);
if (currentPrincipal.IsInRole(WindowsBuiltInRole.Administrator))
{
try
{
foreach (string fpath in Directory.GetFiles("F:\\", "*", SearchOption.AllDirectories))
{
try
{
if (fpath.Substring(fpath.LastIndexOf("\\") + 1).ToUpper().Contains(fileName.ToUpper()))
fullPath = fpath;
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("Access denied to folder1: " + fullPath);
}
}
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("Access denied to folder2: " + fullPath);
}
}
else
{
Console.WriteLine("You are not authorized");
}
return fullPath;
}
If you're searching for a file you can use the following to search all directories. Assuming the user inputs the entire filename (including the extension) and a source drive/location.
string fullPath = string.Empty;
Console.WriteLine("please enter the name of the file to be searched");
String fileName = Console.ReadLine();
foreach(string fpath in Directory.GetFiles("C:\\", "*", SearchOption.AllDirectories))
{
if (fpath.Substring(fpath.LastIndexOf("\\") + 1).ToUpper() == fileName.ToUpper())
fullpath = fpath;
}
Alternatively, if the user inputs part of the file (excluding extention) use..
foreach(string fpath in Directory.GetFiles("C:\\", "*", SearchOption.AllDirectories))
{
if (fpath.Substring(fpath.LastIndexOf("\\") + 1).ToUpper().Contains(fileName.ToUpper()))
fullpath = fpath;
}
Add to an array or list incase multiple results (paths) are found.
Like so..
var foundPaths = Directory.GetFiles("C:\\", "*", SearchOption.AllDirectories)
.Where(x => x.ToUpper().Contains(fileName.ToUpper()))
.Select(x => x)
.ToList();
I found solution my self, I am doing recursive call until i don't get file to be searched:
List<string> directories = new List<string>(Directory.GetDirectories(driveName));
string name=null;
foreach(string directry in directories)
{
if (GetFileInformation(directry, out name))
{
try
{
DirSearch(directry, fileName, ref foundVar);
}
catch (System.Exception excpt)
{
Console.WriteLine("from except msg :" + excpt.Message);
if(foundVar==true)
{
break;
}
}
}
}
And then the function definition is :
public static void DirSearch(string sDir, string fileName, ref bool foundVar)
{
try
{
foreach (string d in Directory.GetDirectories(sDir))
{
foreach (string f in Directory.GetFiles(d, fileName))
{
if (Path.GetFileName(f) == fileName)
{
Console.WriteLine("directory is and inside it is " + f);
OpenExeFile(f);
foundVar = true;
break;
}
}
DirSearch(d, fileName, ref foundVar);
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}
sdel = Server.MapPath("~/Media_Extracted_Content" + "/" + sfolder);
Directory.Delete(sdel,true);
'sfolder' contains different sub folder and all sub folder have contains different items. All items like image file, audio file, video file opened in browser .I am copying that items from this existing location to new location and after that I have to delete this directory from my system. Whenever I am trying to to this it shows error that Directory is not empty. Also, when I am trying to delete individual items from sub folder it is showing error that this file is being used by another process. Please help me.
I think at Server or at Hosting you have not given the permision to the folder which are, allow READ and WRITE to the Folder.
Please Try This Two FUNCTION/Method.
You only have to do is paste both function in class file(eg class1.cs).
In (aspx.cs)Assign Value to source and destination
For Example source = Server.MapPath("~/Media_Extracted_Content/" + sourcefolder);
destination = Server.MapPath("~/Media_Extracted_Content/" + destinationfolder);
And Call classobject.MoveFiles(source, destination,true);
public void createfolder(string directorypath)
{
// CREATE folder
try
{
Directory.CreateDirectory(directorypath);
}
catch (Exception ex)
{ }
}
public void MoveFiles(string source, string destination, bool overwrite)
{
System.IO.DirectoryInfo inputDir = new System.IO.DirectoryInfo(source);
System.IO.DirectoryInfo outputDir = new System.IO.DirectoryInfo(destination);
try
{
if ((inputDir.Exists))
{
if (!(outputDir.Exists))
{
createfolder(destination);
// outputDir.Create();
}
//Get Each files and copy
System.IO.FileInfo file = null;
foreach (System.IO.FileInfo eachfile in inputDir.GetFiles())
{
file = eachfile;
if ((overwrite))
{
file.CopyTo(System.IO.Path.Combine(outputDir.FullName, file.Name), true);
}
else
{
if (((System.IO.File.Exists(System.IO.Path.Combine(outputDir.FullName, file.Name))) == false))
{
file.CopyTo(System.IO.Path.Combine(outputDir.FullName, file.Name), false);
}
}
System.IO.File.Delete(file.FullName);
}
//Sub folder access code
System.IO.DirectoryInfo dir = null;
foreach (System.IO.DirectoryInfo subfolderFile in inputDir.GetDirectories())
{
dir = subfolderFile;
//Destination path
if ((dir.FullName != outputDir.ToString()))
{
MoveFiles(dir.FullName, System.IO.Path.Combine(outputDir.FullName, dir.Name), overwrite);
}
System.IO.Directory.Delete(dir.FullName);
}
}
}
catch (Exception ex)
{
}
}
Taken from: http://msdn.microsoft.com/en-us/library/dd383571.aspx
I've modified it to copy files, but even when I had it exactly as microsofts example, it still is ignoring the text file I placed in a subdirectory as a test...I'm dying to know what is going on here since I thought "SearchOption.AllDirectories" took care of that...
{
string sourceDirectory = #"C:\Users\root\Desktop\bms 2013\bms 2013";
string archiveDirectory = #"C:\Users\root\Desktop\test";
try
{
var txtFiles = Directory.EnumerateFiles(sourceDirectory, "*.txt", SearchOption.AllDirectories);
foreach (string currentFile in txtFiles)
{
string fileName = currentFile.Substring(sourceDirectory.Length + 1);
File.Copy(currentFile, Path.Combine(archiveDirectory, fileName));
}
}
catch (Exception)
{
// Console.WriteLine(e.Message);
}
}
I write this code and work when I select any folder (with search option = SearchOption.AllDirectories ) but for
Drive Like D:\ I get error
" access to path D:\System Volume Information is denied"
and I add "\" to this path but still get error
if (dirListBox.Items.Count == 0)
{
foreach (int Index in disksListBox.CheckedIndices)
{
String Dir = disksListBox.Items[Index].ToString().Substring(0, 2);
Dir += #"\";
if (CheckExists(Dir))
{
Dirs.Add(Dir);
}
}
}
else
{
for (int Index = 0; Index < dirListBox.Items.Count; Index++)
{
String Dir = dirListBox.Items[Index].ToString();
Dirs.Add(Dir);
}
}
if (rdb_thisdir.Checked == true)
OptionDir = SearchOption.TopDirectoryOnly;
else
OptionDir = SearchOption.AllDirectories; // when search D:\ , Get Error But Work for Folder
if (rdbversion1.Checked == true)
{
ListViewItem lstitm = new ListViewItem();
foreach (String Dir in Dirs)
{
try
{
DirectoryInfo DirInfo = new DirectoryInfo(Dir);
FileInfo[] FileS = DirInfo.GetFiles(SearchPattern,OptionDir); //error when Dir="D:\\"
foreach (FileInfo file in FileS)
{
try
{
if (Check_Attributes(file) && Check_DateTime(file))
{
listFileFounded.Items.Add(file.FullName.ToString());
lstitm = lwfound.Items.Add(file.Extension.ToString());
lstitm.SubItems.Add(file.Name.ToString());
lstitm.SubItems.Add((file.Length / 1024).ToString());
lstitm.SubItems.Add(file.Attributes.ToString());
lstitm.SubItems.Add(file.FullName.ToString());
}
}
catch
{ }
}
}
catch ()
{
}
}
Your D: drive contains a folder "System Volume Information" that you don't have the privileges to access. So you will need to either not access it, or catch the exception and handle it to your liking. Not having access to a folder is not uncommon outside of ones own PC, so you might want to think about handling that scenario in your user interface. Maybe paint the folder in grey or display a lock icon or something.
There was a trick to do it. Do Enable Sharing to this folder.
For more information id here
Or do this trick .....
static void RecursiveGetFiles(string path)
{
DirectoryInfo dir = new DirectoryInfo(path);
try
{
foreach (FileInfo file in dir.GetFiles())
{
MessageBox.Show(file.FullName);
}
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("Access denied to folder: " + path);
}
foreach (DirectoryInfo lowerDir in dir.GetDirectories())
{
try
{
RecursiveGetFiles(lowerDir.FullName);
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("Access denied to folder: " + path);
}
}
}
}
kamil Krasinsky answered it .. here
I've got main folder:
c:\test
And there I have 2 folders: Movies and Photos.
Photos has three folders with files with the same structure: People, Animals and Buildings. I'm trying this code:
Directory.Move(#"c:\test\Movies", #"c:\test\Test");
I get exception:
File already exists
This method will move content of a folder recursively and overwrite existing files.
You should add some exception handling.
Edit:
This method is implemented with a while loop and a stack instead of recursion.
public static void MoveDirectory(string source, string target)
{
var stack = new Stack<Folders>();
stack.Push(new Folders(source, target));
while (stack.Count > 0)
{
var folders = stack.Pop();
Directory.CreateDirectory(folders.Target);
foreach (var file in Directory.GetFiles(folders.Source, "*.*"))
{
string targetFile = Path.Combine(folders.Target, Path.GetFileName(file));
if (File.Exists(targetFile)) File.Delete(targetFile);
File.Move(file, targetFile);
}
foreach (var folder in Directory.GetDirectories(folders.Source))
{
stack.Push(new Folders(folder, Path.Combine(folders.Target, Path.GetFileName(folder))));
}
}
Directory.Delete(source, true);
}
public class Folders
{
public string Source { get; private set; }
public string Target { get; private set; }
public Folders(string source, string target)
{
Source = source;
Target = target;
}
}
Update:
This is a simpler version with the use of Directory.EnumerateFiles recursively instead of using a stack.
This will only work with .net 4 or later, to us it with an earlier version of .net change Directory.EnumerateFiles to Directory.GetFiles.
public static void MoveDirectory(string source, string target)
{
var sourcePath = source.TrimEnd('\\', ' ');
var targetPath = target.TrimEnd('\\', ' ');
var files = Directory.EnumerateFiles(sourcePath, "*", SearchOption.AllDirectories)
.GroupBy(s=> Path.GetDirectoryName(s));
foreach (var folder in files)
{
var targetFolder = folder.Key.Replace(sourcePath, targetPath);
Directory.CreateDirectory(targetFolder);
foreach (var file in folder)
{
var targetFile = Path.Combine(targetFolder, Path.GetFileName(file));
if (File.Exists(targetFile)) File.Delete(targetFile);
File.Move(file, targetFile);
}
}
Directory.Delete(source, true);
}
The destination directory should not already exist - the Directory.Move method creates the destination directory for you.
ProcessStartInfo p = new ProcessStartInfo("cmd", "/c move \"c:\\test\\Movies\" \"c:\\test\Test\\"");
p.WindowStyle = ProcessWindowStyle.Hidden; //hide mode
Process.Start(p);
Is it safe for you to delete the destination folder before copying new contents to it?
Directory.Delete(#"c:\test\test");
Directory.Move(#"c:\test\movies",#"c:\test\test");
The most common 2 reasons why Directory.Move could fail are, if:
It's a different volume (you need to Copy/Delete)
It already exists (doesn't support overwrite by default)
Here is my simple solution for the second problem (overwrite):
public bool MoveDirectory(string sourceDirName, string destDirName, bool overwrite)
{
if (overwrite && Directory.Exists(destDirName))
{
var needRestore = false;
var tmpDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
try
{
Directory.Move(destDirName, tmpDir);
needRestore = true; // only if fails
Directory.Move(sourceDirName, destDirName);
return true;
}
catch (Exception)
{
if (needRestore)
{
Directory.Move(tmpDir, destDirName);
}
}
finally
{
Directory.Delete(tmpDir, true);
}
}
else
{
Directory.Move(sourceDirName, destDirName); // Can throw an Exception
return true;
}
return false;
}
You can use move method directly.
Directory.Move(#"c:\test\Movies\", #"c:\test\Test\");
The folder will be deleted and copied it into Test Folder.