I need to delete files with ".bak" and ".csv.bak" extensions. I use .net c#.
I tried like this:
string srcDir = #"D:\Backup";
string[] bakList = Directory.GetFiles(srcDir,".bak");
if (Directory.Exists(srcDir))
{
foreach (string f in bakList)
{
File.Delete(f);
}
}
But when debugging, the bakList array is empty.
Directory.GetFiles() is not loading the file names in the array. I cant figure out what is wrong in my coding.
You need to Add * before your .bak in GetFiles()
string srcDir = #"D:\Backup";
string[] bakList = Directory.GetFiles(srcDir,"*.bak");
if (Directory.Exists(srcDir))
{
foreach (string f in bakList)
{
File.Delete(f);
}
}
If you need to search for both types maybe it works better
var files = Directory.GetFiles(srcDir, "*.*")
.Where(s => s.EndsWith(".bak"));
If your file name is
"Data Logger[2].csv.bak",
go to the properties and check the type of file. it will be something like this
"1 File (.1)" .The file has number as its end extension. So i used like this.
string[] bk = Directory.GetFiles(srcDir, "*.bak.*");
foreach (string f in bk)
{
File.Delete(f);
}
its working...
Related
I have json files that i'm trying to classify so the file names are as such:
inputTestingSetting_test
inputTestingSetting_test1310
inputTestingSetting_test1310_ckf
inputTestingSetting_test1310_ols
inputTestingSetting_test1310_sum
inputTestingSetting_test1311_ckf
inputTestingSetting_test1311_ols
inputTestingSetting_test1311_sum
So the output that i want in the ListBox lbJsonFileNames will be
test
test1310
test1311
currently my codes are
DirectoryInfo dInfo = new DirectoryInfo(tbJSFolder.Text);
FileInfo[] Files = dInfo.GetFiles("*.json");
List<jSonName> jsonName = new List<jSonName>();
foreach (FileInfo file in Files)
{
string filename = Path.GetFileNameWithoutExtension(file.Name);
string[] fileNameSplit = filename.Split('_');
jsonName = new List<jSonName>{
new jSonName(fileNameSplit[0],fileNameSplit[1])
};
for(int i=0;i<jsonName.Count;i++)
{
if(jsonName[i].TestNumber == fileNameSplit[1])
{
lbJsonFileNames.Items.Add(jsonName[i].TestNumber);
}
}
}
so my output for lbJsonFileNames is what i want, however it is repeated. is it possible to just show one? i've tried to put jsonName[i].TestNumber to jsonName[i+1].TestNumber. but failed as it is out of range.
is there a way to read the file names, and then compare it with the previous file name to see if it is the same? and if it is the same, ignore, move on to the next file name, if it's different then it is added into the ListBox
changed my codes to
DirectoryInfo dInfo = new DirectoryInfo(tbJSFolder.Text);
FileInfo[] Files = dInfo.GetFiles("*.json");
List<jSonName> jsonName = new List<jSonName>();
HashSet<string> fileNames = new HashSet<string>();
foreach (FileInfo file in Files)
{
string filename = Path.GetFileNameWithoutExtension(file.Name);
string[] fileNameSplit = filename.Split('_');
fileNames.Add(fileNameSplit[1]);
}
foreach(var value in fileNames)
{
lbJsonFileNames.Items.Add(value);
}
got what i want now thanks all~
Your code basically says to put the following into list box:
test
test1310
test1310
test1310
test1310
test1311
test1311
test1311
Before you add as in lbJsonFileNames.Items.Add(jsonName[i].TestNumber);, check for duplicate first. Maybe you can put that list into a Set variable. Set will automatically remove the duplicate. Then put the Set back to lbJsonFileNames.
[Edit] Sorry there is no Set in dot net. Please use HashSet instead.[/Edit]
Your code did not mention what jSonName class is like and the constructor parameters stand for. However to get your output from your input can be much easier:
string[] all = Directory.GetFiles(tbJSFolder.Text, "*.json")
.Select(x => Path.GetFileNameWithoutExtension(x))
.Select(x => x.Split(new char[] { '_' })[1])
.Distinct().ToArray();
lbJsonFileNames.Items.AddRange(all);
I have a folder that contains these files:
Erb3PCustsExport-303_20080318_223505_000.xml
Erb3PCustsExport-303_20080319_063109_000_Empty.xml
Erb3PCustsImport-303_20080319_123456.xml
Erb3PDelCustsExport-303_20080319_062410_000.xml
Erb3PResosExport-303_20080318_223505_000_Empty.xml
Erb3PResosExport-303_20080319_062409_000.xml
I just care about the files that have CustsExport word in their names.
My question:
How to get these files?
What I have tried:
I got the folder name from app settings section in App.Config like this:
string folderPath = ConfigurationManager.AppSettings["xmlFolder"];
Then I got all the file names like this:
foreach (string file in Directory.EnumerateFiles(folderPath, "*.xml"))
{
}
My problem:
In that way, I got all the files. However, I am just interested in files that have CustsExport in their names.
Could you help me please?
Note:
I am working on .NET 4.5
Try this:
foreach (string file in Directory.EnumerateFiles(folderPath, "*CustsExport*.xml"))
{
}
Or your can use regex:
Regex reg = new Regex(#".*CustsExport.*\.xml",RegexOptions.IgnoreCase);
var files = Directory.GetFiles(yourPath, "*.xml")
.Where(path => reg.IsMatch(path))
.ToList();
You can use string.Contains("")
string folderPath = ConfigurationManager.AppSettings["xmlFolder"];
foreach (string file in Directory.EnumerateFiles(folderPath, "*.xml"))
{
if (file.Contains("CustsExport"))
{
//add your code
}
}
I have two folders : FolderA and FolderB
I want to delete the files in FolderA which also exist in FolderB. (i.e. Common files will be deleted from folderA)
How can I do this most efficiently in C#? (That's a critical point in the project and it has to be as efficient as possible )
Thanx
This is easy, readable and also efficient:
var common = from f1 in Directory.EnumerateFiles(folderA, "*.*", SearchOption.AllDirectories)
join f2 in Directory.EnumerateFiles(folderB, "*.*", SearchOption.AllDirectories)
on Path.GetFileName(f1) equals Path.GetFileName(f2)
select f1;
foreach (string file in common)
{
File.Delete(file);
}
Assuming that you just want to compare the file names (and extension).
You can do this with the help of LINQ. See here.
If you only want to compare file names, here is how you can do it, I did a quick test of this code and it works:
string pathA = #"C:\New FolderA";
string pathB = #"C:\New FolderB";
var filesA = Directory.GetFiles(pathA).Select(path => Path.GetFileName(path));
var filesB = Directory.GetFiles(pathB).Select(path => Path.GetFileName(path));
var toBeDeleted = filesA.Intersect(filesB);
foreach (string filename in toBeDeleted)
File.Delete(Path.Combine(pathA, filename));
string[] FolderAFiles = Directory.GetFiles(#"Path");
string[] FolderBFiles = Directory.GetFiles(#"BPath");
foreach (string Files in FolderAFiles)
{
if (FolderBFiles.Contains(Files))
{
File.Delete(Files);
}
}
Try this
Here's one another solution.
var filesInB = System.IO.Directory.GetFiles("FolderB");
Array.ForEach(System.IO.Directory.GetFiles("FolderA"), delegate(string fileName){
if (filesInB.Contains(fileName)) System.IO.File.Delete(fileName);
});
I would like to be able to iterate through the name of some image files in a folder using c#. So for intance I have a folder named image and contains the following images
image
dog.jpg
cat.jpg
horse.jpg
I want to be able to go through the names and be able to say
if(filename == dog.jpg)
return true
else
return false
Something of that nature
Thank you
You should use the static Exists method on System.IO.File.
return System.IO.File.Exists("dog.jpg")
Since the method returns a boolean, there is no need for the if statement in the example you gave.
You can also use a bit of Linq magic to determine if a file exists in a folder structure, like this:
var dir = new System.IO.DirectoryInfo(startFolder);
var fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories);
bool fileExists = fileList.Any(f => f.FullName == "dog.jpg");
or even shorter:
return System.IO.Directory
.GetFiles(#"c:\myfolder", "dog.jpg", SearchOption.AllDirectories)
.Any();
which would search the folder specified and all subfolder with the pattern "dog.jpg". The Any() extension method simply checks whether the IEnumerable contains any items. I think this is the most efficient way of doing this (based on gut feeling).
From http://weblogs.asp.net/israelio/archive/2004/06/23/162913.aspx Just insert your if in the "// do something with filename" area:
// How much deep to scan. (of course you can also pass it to the method)
const int HowDeepToScan=4;
public static void ProcessDir(string sourceDir, int recursionLvl)
{
if (recursionLvl<=HowDeepToScan)
{
// Process the list of files found in the directory.
string [] fileEntries = Directory.GetFiles(sourceDir);
foreach(string fileName in fileEntries)
{
// do something with fileName
Console.WriteLine(fileName);
}
// Recurse into subdirectories of this directory.
string [] subdirEntries = Directory.GetDirectories(sourceDir);
foreach(string subdir in subdirEntries)
// Do not iterate through reparse points
if ((File.GetAttributes(subdir) &
FileAttributes.ReparsePoint) !=
FileAttributes.ReparsePoint)
ProcessDir(subdir,recursionLvl+1);
}
}
get all the files
string[] filePaths = Directory.GetFiles(#"c:\yourfolder\");
and iterate through it
use Directory.GetFiles()
foreach(var file in (myDir.GetFiles("*.jpg")
{
if(file.Name == "dog.jpg") return true;
}
var files = System.IO.Directory.GetFiles("directory", "*.jpg");
foreach (var item in files)
{
if (System.IO.Path.GetFileName(item) == "dog.jpg")
{
// File found.
}
}
DirectoryInfo di = new DirectoryInfo("c:\\Images");
var files = di.GetFiles("*.jpg");
foreach (var fileInfo in files)
{
if (fileInfo.Name == "dog.jpg")
return true;
}
return false;
I am trying to get titles of xml files from a folder call "bugs".
My code:
public virtual List<IBug> FillBugs()
{
string folder = xmlStorageLocation + "bugs" + Path.DirectorySeparatorChar;
List<IBug> bugs = new List<IBug>();
foreach (string file in Directory.GetFiles(folder, "*.xml", SearchOption.TopDirectoryOnly))
{
var q = from b in bugs
select new IBug
{
Title = b.Title,
Id = b.Id,
};
return q.ToList();
}
return bugs;
}
But I'm not geting out the titles from all the xml files in the folder "bugs".
the biggest problem is to get eatch files to singel string and not string[].
Your code as written doesn't make any sense. Perhaps you meant something more like this:
public virtual List<IBug> FillBugs()
{
// is this actually correct or did you mix up the concatenation order?
// either way, I suggest Path.Combine() instead
string folder = xmlStorageLocation + "bugs" + Path.DirectorySeparatorChar;
List<IBug> bugs = new List<IBug>();
foreach (string file in Directory.GetFiles(folder, "*.xml",
SearchOption.TopDirectoryOnly))
{
// i guess IBug is not actually an interface even though it starts
// with "I" since you made one in your code
bugs.Add(new IBug {
Title = file, Id = 0 /* don't know where you get an ID */ });
}
return bugs;
}
"from b in bugs" selects from an empty list. you need to initialize bugs from the file at the start of your foreach loop
Do you need a backslash (Path.DirectorySeparatorChar) between xmlStorageLocation and "bugs"?
You don't use file in your loop anywhere - Is that correct or did you miss to push it into the collection?