how can delete folders in c sharp - c#

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.

Related

c# delete all files but not last one

i am trying to delete all images in image directory except the last image loaded in picture box and using th following code to achive this but still getting file in use exception
System.IO.DirectoryInfo di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "\\Images\\");
foreach (FileInfo file in di.GetFiles())
{
if(file.FullName!=pictureBoxLoadImage.ImageLocation)
file.Delete();
}
This should work, it skips the last file from the files and delete the remaining
System.IO.DirectoryInfo di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "\\Images\\");
var files = di.GetFiles();
files.AsParallel().Reverse().Skip(1).ForAll((f) => f.Delete());
I think ImageLocation here returns the relative paths of your images, that will make your if statement returns true always even for the last image, to fix this you should convert the path returned by ImageLocation to the absolute path:
System.IO.DirectoryInfo di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "\\Images\\");
foreach (FileInfo file in di.GetFiles())
{
if(file.FullName!= Path.GetFullPath(pictureBoxLoadImage.ImageLocation))
file.Delete();
}

Copy all files from a directory without creating subdirectories

I am trying to take a directory and create a new directory in TEMP, that contains all the files in the original directory, but not create additional sub-directories.
Here is what I have so far:
Directory.CreateDirectory(Path.Combine(Path.GetTempPath() + "C# Temporary Files"));
string lastFolder = new DirectoryInfo(folders.SelectedPath).Name;
foreach (string newPath in Directory.GetFiles(folders.SelectedPath, "*.*",SearchOption.AllDirectories)
.Where(s=>s.EndsWith(".c")|| s.EndsWith(".h")))
{
File.Copy(newPath, newPath.Replace(folders.SelectedPath, Path.GetTempPath() + "C# Temporary Files\\" + GlobalVar.GlobalInt));
}
This works in copying files that are in the directory itself, but not files in subdirectories. Instead it throws the error:
System.IO.DirectoryNotFoundException.
An example of the error:
Could not find a part of the path
'C:\Users\username\AppData\Local\Temp\C# Temporary Files\outer
directory\sub-directory\filename'.
I'd it recursively - maybe something like the below pseudo code... not tested..
public void CopyRecursive(string path, string newLocation)
{
foreach(var file in DirectoryInfo.GetFiles(path))
{
File.Copy(file.FullName, newLocation + file.Name);
}
foreach(var dir in DirectoryInfo.GetDirectories(path))
{
CopyRecursive(path + dir.Name, newLocation);
}
}

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

Exception when trying to delete a directory in Isolated Storage

I get the following exception when I try to delete a directory in Isolated Storage in Windows Phone 7:
An error occurred while accessing IsolatedStorage.
there is no inner exception.
using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
{
isf.DeleteDirectory(dir.TrimEnd('/'));
}
Notes:
putting it in a try-catch will hide the exception but still directory is not deleted!
before calling this I delete all files inside that using DeleteFile() so the problem can not be related to existing files inside the directory.
trimming the directory name is to make sure it's a valid directory name.
Any idea?
Thanks.
Ok, problem solved, problem was that files were not being deleted correctly. The reason I was confused is that IsolatedStorageFile class does not warn you when you are deleting an invalid file. here is the correct code and some notes:
public static void DeleteDirectoryRecursive(this IsolatedStorageFile isf, string dir)
{
foreach (var file in isf.GetFileNames(dir))
{
isf.DeleteFile(dir + file);
}
foreach (var subdir in isf.GetDirectoryNames(dir))
{
isf.DeleteDirectoryRecursive(dir + subdir + "\\");
}
isf.DeleteDirectory(dir.TrimEnd('\\'));
}
Notes:
there is no difference between '\' and '/' in file paths
trimEnd() is required when DeleteDirectory otherwise exception "path must be a valid file name" is thrown.
GetFileNames() and GetDirectoryNames() return only the name part not the full path. so in order to use each result you need to combine it with the directory (DeleteFile() in this example)
According to your code and your description, you would be recreating the IsolatedStorageFile access on every iteration?
You should post all the code, since the error isn't related to what you told so far. As for a working example, see this blog post. If that fails with your directory name, you're clearly doing something wrong.
Also, I believe it uses backslashes, not forward-slashes for paths, so your Trim() would be rather useless either way.
`public static void DeleteDirectoryRecursive(string directory, IsolatedStorageFile store)
{
if (!store.DirectoryExists(directory))
return;
var pattern = Path.Combine(directory, "*");
foreach (var file in store.GetFileNames(pattern))
{
store.DeleteFile(Path.Combine(directory, file));
}
foreach (var folder in store.GetDirectoryNames(pattern))
{
DeleteDirectoryRecursive(Path.Combine(directory, folder), store);
}
store.DeleteDirectory(directory);
}`
Thanks to valipour, I solved the problem
foreach (var file in isf.GetFileNames(dir))
{
isf.DeleteFile(dir + file);
}
In my case the variable dir is "images". In order to get all file names in "images" directory, you should use isf.GetFileNames("images/*")
Grabbed Valipour's version and make it work. Added some checks to improve stability + fixed some names. This works for me on Lumia 920.
private void DeleteDirectoryRecursive(string dir)
{
if (String.IsNullOrEmpty(dir)) return;
try
{
using (var isoFiles = IsolatedStorageFile.GetUserStoreForApplication())
{
foreach (var file in isoFiles.GetFileNames(dir + "\\*"))
{
var filename = dir + "/" + file;
if (isoFiles.FileExists(filename))
isoFiles.DeleteFile(filename);
}
foreach (var subdir in isoFiles.GetDirectoryNames(dir))
{
var dirname = dir + subdir + "\\";
if (isoFiles.DirectoryExists(dirname))
DeleteDirectoryRecursive(dirname);
}
var currentDirname = dir.TrimEnd('\\');
if (isoFiles.DirectoryExists(currentDirname))
isoFiles.DeleteDirectory(currentDirname);
}
}
catch (Exception e)
{
throw;
}
}

C# - Search for Matching FileNames in a Directory using SearchOption

Background: I'm developing a WinForms application using C# with an OpenFileDialog & FileBrowserDialog that will 1) search for a specific string in the filenames of a specified source directory 2) copy files to consolidated directory 3) convert multiple files from excel to csv files, and then 3) convert all the generated csv files into 1 big csv file using a command line executable
Example: MSDN provides a code example that lists all of the directories and files that begin with the letter "c" in "c:\". at http://msdn.microsoft.com/en-us/library/ms143448.aspx so I based my code on that...
Problem: The code doesn't copy any files to the consolidated folder so I'm pretty sure the search doesn't work.
What should I change on here? It doesn't work :
string files = "*.xlsx";
void DirSearch(string sDir)
{
try
{
foreach (string d in Directory.GetDirectories(sDir))
{
foreach (string f in Directory.GetFiles(d, files))
{
// Is this the file we are looking for?
// check excel files for corp name in the filename.
if (f.Contains(m_sc.get_Corp()))
{
// check if thread is cancelled
if (m_EventStop.WaitOne(0, true))
{
// clean-up operations may be placed here
// ...
// inform main thread that this thread stopped
m_EventStopped.Set();
return;
}
else
{
string path = sDir;
string searchPattern = m_sc.get_Corp();
// A file has been found in this directory
DirectoryInfo di = new DirectoryInfo(path);
DirectoryInfo[] directories = di.GetDirectories(searchPattern, SearchOption.TopDirectoryOnly);
foreach (FileInfo file in files)
{
try
{
// Copy each selected xlsx files into the specified TargetFolder
System.IO.File.Copy(FileName, consolidatedFolder + #"\" + System.IO.Path.GetFileName(FileName));
Log("File" + FileName + " has been copied to " + consolidatedFolder + #"\" + System.IO.Path.GetFileName(sourceFileOpenFileDialog.FileName));
// Convert each selected XLSX File to CSV Using the command prompt code...
}
}
}
}
The code you've posted does two separate search loops:
first:
foreach (string d in Directory.GetDirectories(sDir))
{
foreach (string f in Directory.GetFiles(d, files))
{
// Is this the file we are looking for?
// check excel files for corp name in the filename.
if (f.Contains(m_sc.get_Corp()))
{
then within that it also does:
string path = sDir;
string searchPattern = m_sc.get_Corp();
// A file has been found in this directory
DirectoryInfo di = new DirectoryInfo(path);
DirectoryInfo[] directories = di.GetDirectories(searchPattern, SearchOption.TopDirectoryOnly);
foreach (FileInfo file in files)
{
In the first one you are looking for files matching m_sc.get_Corp();, in the second one you are lookinf for directories...
In fact... your code (pseudo-code?) makes no sense...
Try:
taking your time
tidying up the code yourself
if you rewrite it slowly and break this into smaller chunks, you might spot what you are doing wrong.
Try cleaning up a bit, below is some code that will put you on the path, I've excluded the CSV conversion and the merge, hopefully you will get the idea.
private void YourFileRoutine(string sourceDirectoryPath, string consolidatedDirectoryPath)
{
var excelFiles = new DirectoryInfo(sourceDirectoryPath).GetFiles().Where(x => x.Extension == ".xlsx");
//Copy all Excel Files to consolidated Directory
foreach (var excelFile in excelFiles)
{
FileInfo copiedFile = excelFile.CopyTo(String.Concat(consolidatedDirectoryPath, excelFile.Name)); // Make sure consolidatedDirectoryPath as a "\" maybe use Path.Combine()?
// ConvertToCSV( Do your CSV conversion here, the Path will be = Path.GetFullPath(copiedFile);
}
// Merge CSV's
var csvFiles = new DirectoryInfo(consolidatedDirectoryPath).GetFiles().Where(x => x.Extension == ".csv");
// SomeMergeMethod that iterates through this FileInfo collection?
}

Categories

Resources