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();
}
Related
I have this project where I'm iterating recursively in some folders and copy them to a new directory.
In the 2nd level of folders (child folder) I have a txt file which I am reading. Now, when I read that file, I parse a string and I want to give that string to the parent folder and assign it as its name. So far I can only do for its File only, because there is accessible but when I try to do it for the parent folder, it doesn't recognize the variable (which of course, makes sense!)
EDIT: I commented the code so it will be a little bit clearer.
Now, Is there any way I can achieve this?
Here's my code:
static void CopyDirectory(string sourceDir, string destinationDir, bool recursive)
{
//accessing the directiories inse of Destionationed directory
DirectoryInfo[] dirs = dir.GetDirectories();
Directory.CreateDirectory(destinationDir);
if (recursive)
{
// reading every folder inside first parent folder
foreach (DirectoryInfo subDir in dirs)
{
//reading every folder inside the second folder
DirectoryInfo[] Subdirs = subDir.GetDirectories();
foreach (DirectoryInfo subDir2 in Subdirs)
{
//setting the new path where I want my new files to be stored.
string newDestinationDir = Path.Combine(destinationDir, subDir2.Name);
//Now, here its where I want to change the main folder's name, but the value must be taking from inside it's file.
CopyDirectory(subDir2.FullName, newDestinationDir, true);
FileInfo[] SubDirsFiles = subDir2.GetFiles();
foreach (FileInfo getFile in SubDirsFiles)
{
File.Copy(getFile.FullName, newDestinationFile + "_" + dictionary["XECM_DOC_TYPE"], true);
}
}
}
}
}
Note: I'm using Dictiony to story the data I read from file, and thats what I'm trying to pass to the parent folder, exclusively-to the CopyDirectory(subDir2.FullnName,NewDestinationDir+dictionary["XECM_DOC_TYPE"],true) but logically it can't recognize the dictionary part because it is declared and initialized inside the FileInfo part...
I hope I was clear enough.
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.
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 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))
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?
}