string[] dirs = System.IO.Directory.GetDirectories(#"C:\Somefolder\");
foreach (string dir in dirs)
{
listBox1.Items.Add(Path.GetFileName(dir));
}
This is my code, and I have no idea how to get ONLY directories which contains name of something in my textbox for example. I have seen that someone had textbox, next to it button update, I tried to do it the same way - you write into textbox name of a folder ex. Windows and it shows ONLY the one folder so if I write Sys it will find System32 and SYSWOW64 && it wont be case sensitive cause I can do simple if condition, but cant make it not case sensitive you know what I mean? my english is pretty bad, had to tell it this way hope its understandable
Probably, you want this
string[] dirs = System.IO.Directory.GetDirectories(#"C:\Somefolder\");
foreach (string dir in dirs.Where(x => x.Contains(textBox1.Text)))
{
listBox1.Items.Add(Path.GetFileName(dir));
}
EDIT
string[] dirs = System.IO.Directory.GetDirectories(#"C:\Somefolder\");
foreach (string dir in dirs.Where(x => x.ToLower().Contains(textBox1.Text.Trim().ToLower())))
{
listBox1.Items.Add(Path.GetFileName(dir));
}
Related
I want to create a program that gets all the .pdf-filenames (ex: test.pdf -> test) and creates an folder with that name. Also the foldername should be cropped after the first "-" (ex: A539B2AA3-GG-81234278 -> A539B2AA3).
This is the code I have made yet, but I have no clue how to proceed. I'm still a beginner, trying to learn C#:
string path = #"C:\pdfs\";
string[] filenames;
int lengtharray;
filenames = Directory.GetFiles(path, "*", SearchOption.TopDirectoryOnly)
.Where(s => (Path.GetExtension(s).ToLower() == ".pdf")).ToArray();
lengtharray = filenames.Length;
If someone can help me, I would be very happy.
Sincerely,
breadhead
You can use this code.
1) Directory.GetFiles has a wildcard support, so you can use *.pdf to search for file.
2) I added some validation in the loop, in case there are PDF file that does not have -.
string path = #"C:\pdfs\";
foreach(var file in Directory.GetFiles(path, "*.pdf", SearchOption.TopDirectoryOnly))
{
var newName = Path.GetFileName(file).Split('-');
if (!newName.Any())
continue;
Directory.CreateDirectory(Path.Combine(path,newName[0]));
}
You can simplify your file query, use filenames = Directory.GetFiles(path, "*.pdf", .... and skip the Where()-part. To loop through your list, you can use a foreach (file in filenames). As mentioned you can get the new filename with file.Split("-")[0] or with a regular expression. Then create a directory with Directory.CreateDirectory and move the file in with System.IO.File.Move("oldfilename", "newfilename");. Now you have all the bricks and you only need to glue them together
I want to loop through all sub folders and files in a folder and check whether a particular filename contains a folder say "X" in its path (ancestor). I dont want to use string comparison.Is there a better way?
Answering your specific question (the one that is in the title of your question, not in the body), once you have the filename (which other answers tell you how to find), you can do:
bool PathHasFolder(string pathToFileName, string folderToCheck)
{
return Path.GetDirectoryName(pathToFileName)
.Split(Path.DirectorySeparatorChar)
.Any(x => x == folderToCheck);
}
This will work only with absolute paths... if you have relative paths you can complicate it further (this requires the file to actually exist though):
bool PathHasFolder(string pathToFileName, string folderToCheck)
{
return new FileInfo(pathToFileName)
.Directory
.FullName
.Split(Path.DirectorySeparatorChar)
.Any(x => x == folderToCheck);
}
You can use Directory.GetFiles()
// Only get files that begin with the letter "c."
string[] dirs = Directory.GetFiles(#"c:\", "c*");
Console.WriteLine("The number of files starting with c is {0}.", dirs.Length);
foreach (string dir in dirs)
{
Console.WriteLine(dir);
}
https://msdn.microsoft.com/en-us/library/6ff71z1w(v=vs.110).aspx
You can use recursive search like
// sourcedir = path where you start searching
public void DirSearch(string sourcedir)
{
try
{
foreach (string dir in Directory.GetDirectories(sourcedir))
{
DirSearch(dir);
}
// If you're looking for folders and not files take Directory.GetDirectories(string, string)
foreach (string filepath in Directory.GetFiles(sourcedir, "whatever-file*wildcard-allowed*"))
{
// list or sth to hold all pathes where a file/folder was found
_internalPath.Add(filepath);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
So in your case you're looking for folder XYZ, use
// Takes all folders in sourcedir e.g. C:/ that starts with XYZ
foreach (string filepath in Directory.GetDirectories(sourcedir, "XYZ*")){...}
So if you would give sourcedir C:/ it would search in all folders available on C:/ which would take quite a while of course
This is a lot, I know; trying to dig myself out of a hole at work.
Basically, I have many files across multiple servers that I need to get a hold of. Right now I'm running in to two problems, 1) I can't figure out the best way to search through multiple UNC paths. 2) I'm having to search by a partial name, it's possible that there is more than one file that matches, but I only want to use the file created in the last three days.
Here is my code so far. I'm not looking for someone to write it, but I would appreciate any logistical pointers.
uncPath1 = "\\server\share\";
string partial = "2002265467";
DateTime date = Convert.ToDateTime("10/5/2015");
DirectoryInfo a = new DirectoryInfo(uncPath1);
FileInfo[] interactionlist = a.GetFiles("*" + partial + "*.*", SearchOption.AllDirectories);
foreach (FileInfo f in interactionlist)
{
string fullname = f.FullName;
Console.WriteLine(fullname);
Console.Read();
}
You mentioned that you need to find only files made in the past 3 days. Instead of using Convert.ToDateTime and hard-coding the date in, you should use DateTime.Today.AddDays( -3 ) to get the date three days before the day the program is being run.
And of course, in your finding files method, compare the dates with something like:
DateTime time = DateTime.Today.AddDays( -3 );
if ( File.GetCreationTime( filePath ) > time ) {
// Add the file
}
1) You want to make a basic function that looks for a filespec in a single folder. You already wrote that in your code above, you just need to turn it into a function with parameters UNC path and filespec. Have the function take a third parameter of List<FileInfo> to add found files to.
2) If you need to search subfolders, create a function that will search a UNC path's subfolders by calling the function you wrote in #1, then getting a list of all folders, and calling itself for each folder found (and in turn, those calls will call for sub-subfolders, etc.) This is called recursion. Have this function take a List and add all found files to the List, by passing it to your #1 function.
3) Get the root UNC paths you want to search into a List or Array and then call foreach on them passing them, the filespec, and the intially empty List to the #2 function.
So:
bool FindFiles(string uncPath, string fileSpec, List<FileInfo> found);
bool FildFilesSubfolders(string uncPath, string fileSpec, List<FileInfo> found);
string fileSpec = "whatever";
string[] uncPaths = { "abc", "def" }; // etc
List<FileInfo> found = new List<FileInfo>();
foreach (string nextPath in uncPaths)
{
if (FindFilesSubfolders(nextPath, fileSpec, found))
break;
}
foreach (FileInfo f in found)
{
string fullname = f.FullName;
Console.WriteLine(fullname);
Console.Read();
}
One final thought: if you are searching subdirs and you are worried about two UNC paths that are essentially duplicates (e.g., c:\foo and c:\foo\foo2), you can use This method to check for paths within another path.
Edit: If you find something you are looking for and want to exit early, have the functions return a boolean meaning you found what you wanted to stop early. Then use break in your loops. I've edited the code.
I have a folder structure similar to this:
HostnameA->DateTimeA->hashdumpDateTimeA.txt
HostnameA->DateTimeB->hashdumpDateTimeB.txt
HostnameA->DateTimeC->hashdumpDateTimeC.txt
HostnameA->DateTimeD->hashdumpDateTimeD.txt
My Goal:
Given a folder(in this case HostnameA) i need to:
1) Get each hashdumpDateTime.txt filename and place it in a String array -Assumed the file always exist in all folder-
2) Generate DropDownBox using the array (I can figure this out)
3) When user selects a filename via dropdownbox, it will fill my datagridview with the
contents (I can figure this out)
So my problem really is the #1 since i don't know how to make a loop to check the filename coming from a HostnameA folder, I need to know this since the DateTime of these filenames changes
I really appreciate the future help, thanks and cheers =)
You can use Directory.GetFiles method
var files = Directory.GetFiles("directoryPath","*.txt",SearchOption.AllDirectories)
That will give you all file names.If you don't want just names for example if you want file's full path, and some other attributes (like CreationTime, LastAccessTime) use DirectoryInfo class
DirectoryInfo di = new DirectoryInfo("path");
var files = di.GetFiles("*.txt",SearchOption.AllDirectories)
That will return an array of FileInfo instances.Then use a loop and do what you want with the files.
You doesn't need to know the exact name of DirectoryName or FileName, using a for loop and a searchPattern instead.
private string[] GetFileNames(string folder)
{
var files = new List<string>();
foreach (var dateTimeFolder in Directory.GetDirectories(folder))
{
files.AddRange(Directory.GetFiles(dateTimeFolder, "hashdump*.txt"));
}
return files.ToArray();
}
If I have a string variable that has:
"C:\temp\temp2\foo\bar.txt"
and I want to get
"foo"
what is the best way to do this?
Use:
new FileInfo(#"C:\temp\temp2\foo\bar.txt").Directory.Name
Far be it for me to disagree with the Skeet, but I've always used
Path.GetFileNameWithoutExtension(#"C:\temp\temp2\foo\bar.txt")
I suspect that FileInfo actually touches the file system to get it's info, where as I'd expect that GetFileNameWithoutExtension is only string operations - so performance of one over the other might be better.
I think most simple solution is
DirectoryInfo dinfo = new DirectoryInfo(path);
string folderName= dinfo.Parent.Name;
Building on Handleman's suggestion, you can do:
Path.GetFileName(Path.GetDirectoryName(path))
This doesn't touch the filesystem (unlike FileInfo), and will do what's required. This will work with folders because, as the MSDN says:
Return value: The characters after the last directory character in path. If the last
character of path is a directory or volume separator character, this
method returns String.Empty. If path is null, this method returns
null.
Also, looking at the reference source confirms that GetFilename doesn't care if the path passed in is a file or a folder: it's just doing pure string manipulation.
I had an occasion when I was looping through parent child directories
string[] years = Directory.GetDirectories(ROOT);
foreach (var year in years)
{
DirectoryInfo info = new DirectoryInfo(year);
Console.WriteLine(info.Name);
Console.WriteLine(year);
//Month directories
string[] months = Directory.GetDirectories(year);
foreach (var month in months)
{
Console.WriteLine(month);
//Day directories
string[] days = Directory.GetDirectories(month);
foreach (var day in days)
{
//checkes the files in the days
Console.WriteLine(day);
string[] files = Directory.GetFiles(day);
foreach (var file in files)
{
Console.WriteLine(file);
}
}
}
}
using this line I was able to get only the current directory name
DirectoryInfo info = new DirectoryInfo(year);
Console.WriteLine(info.Name);
It'll depend on how you want to handle the data, but another option is to use String.Split.
string myStr = #"C:\foo\bar.txt";
string[] paths = myStr.Split('\\');
string dir = paths[paths.Length - 2]; //returns "foo"
This doesn't check for an array out of bounds exception, but you get the idea.