I want to know which folder contains files which have a $ in their names.
But I will get duplicate folder names if I use this code:
string local = #"C:\test\";
string[] dirs = Directory.GetFiles(local, "*$*", SearchOption.AllDirectories);
foreach(string dir in dirs)
{
string a = Path.GetFileName(Path.GetDirectoryName(dir));
}
This is the content of the test folder:
C:\test\20170321\$123.txt
C:\test\20170321\2$4.txt
C:\test\20170322\567.txt
C:\test\20170322\abc.txt
should be get result only 1 20170321
This should do it:
string local = #"C:\test\";
string[] dirs = Directory.GetFiles(local, "*$*", SearchOption.AllDirectories);
List<string> singleDirNames = dirs.Select(x=> Path.GetDirectoryName(x)).Distinct().ToList();
Explanation: Select from all filenames the directory and take only the distinct values of it into a list
EDIT:
As I just realized, you don't want the entire path, so to get the result from your post you need to use the Path.GetFileName() (there should be another way, I am looking for it):
List<string> singleDirNames = dirs
.Select(x=> Path.GetFileName(Path.GetDirectoryName(x)))
.Distinct().ToList();
Found it. Here would be actually the direct way to access the containing folder inspired by this answer:
List<string> singleDirNames = dirs.Select(x=> new FileInfo(x).Directory.Name)
.Distinct().ToList();
Related
I have an array with of folders in a Directory.
I want them displayed in the combo-box but I don't the full directory to display, I just want the folder names in the directory.
I haven't been successful with what I have tried
MY CODE
string[] filePaths = Directory.GetDirectories(#"\\Mgsops\data\B&C_Poker_Builds\Release_Location\Integration\SDL\SP\Prima\");
ProjectDir.DataSource = filePaths;
ProjectDir.SelectedItem.ToString();
MY RESULT
Look at the DirectoryInfo class - you can do something like this:
string folder = new DirectoryInfo(path).Name;
To get an array (using System.Linq), you could do the following:
string[] filePaths = Directory.GetDirectories("<yourpath>").Select(d => new DirectoryInfo(d).Name).ToArray();
Or, even use the DirectoryInfo class to enumerate your directories:
DirectoryInfo dir = new DirectoryInfo("<yourpath>");
string[] filePaths = dir.GetDirectories().Select(d => d.Name).ToArray();
So I know how to store the full path but not just the end folder names, for example I've already got an array but is there any method to remove certain characters from all arrays or just get folder names from a path?
Edit: string[] allFolders = Directory.GetDirectories(directory);
That's what I use to get all folder names but that gets me the whole path
Edit:They need to be stored in an Array
Edit: sorry , I need an array with values such as "mpbeach","blabla","keyboard" and not E:\Zmod\idk\DLC List Generator\DLC List Generator by Frazzlee\ , so basically not the full path
This works.
string[] allFolders = Directory.EnumerateDirectories(directory)
.Select(d => new DirectoryInfo(d).Name).ToArray();
This also works. Difference is we are using List<string> instead of string[]
List<string> allFolders = Directory.EnumerateDirectories(directory)
.Select(d => new DirectoryInfo(d).Name).ToList();
Example 1: Uses string[] allFolders
Test Folder
In VS IDE, in Debug Mode
Example 2: Uses List<string> allFolders
Test Folder
In VS IDE, in Debug Mode
Example 2: Uses string[] allFolders
No need for string operations... Just use DirectoryInfo class
var allFolders = new DirectoryInfo(directory).GetDirectories()
.Select(x => x.Name)
.ToArray();
NOTE I'm taking your question to mean how to extract the last folder name from a file URL. Others are reading this as how to extract the names of folders in a directory. If I'm wrong, it's because I'm misinterpreting your question.
Split by backslash to get folders. The next-to-last value is the last folder:
string folder = #"c:\mydrive\testfolder\hello.txt";
string[] parts = folder.Split('\\');
string lastFolder = parts[parts.Length - 1];
//Yields "testfolder";
Moving that forward to what you want:
private string[] foldersOnly(){
List<string> folders = new List<string>();
string[] allFolders = Directory.GetDirectories(directory);
foreach(string folder in allfolders){
string[] parts = folder.Split('\\');
folders.Add(parts[parts.Length-1]);
}
}
return folders.ToArray();
I need to list all directories from a path. I need to get only last subdirectory path and not all paths.
i.e. for
pathbase/2016/01
I don't need pathbase/2016 but pathbase/2016/01
Now I'm using this code:
List<string> dirs = new List<string>(Directory.EnumerateDirectories(pathBase));
string[] entries = System.IO.Directory.GetDirectories(pathBase, "*",
SearchOption.AllDirectories);
var listDir = from dir
in entries
return listDir.ToList();
What type of filter can i use in Linq to exclude this directory?
Thanks.
Do you mean you need all leafs directories (directories that don't have subdirectories)?
If so this should do it
// First off, don't use GetDirectories on the static Directory class, it returns a string path and not a DirectoryInfo which isn't very usefull here, instead create a DirectoryInfo and go from there:
var RootDirectory = new DirectoryInfo(pathBase);
// Then queries all of it's subdirectories and filter on those
var listDir = RootDirectory.GetDirectories("*",SearchOption.AllDirectories)
.Where(dir=>!dir.GetDirectories().Any())
.ToList();
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 directory which is present at #"F:\\Unzip\\" .This directory will contain a folder.Now as per my requirement i want to move the folder inside it to some other directory but i am not able to get it.Here is the code that i tried to read the folder name present in the directory but it is reading the file present in the folder.
if (Directory.Exists(#"F:\\Unzip\\") == true)
{
//Get the file name
List<String> files = Directory.GetFiles(#"F:\Unzip\", "*.*", SearchOption.AllDirectories).ToList();
string strr=files[0].ToString();
}
Please help me to move the folder present inside the directory.Thanks
You can try like this:
List<string> lst = new List<string>();
DirectoryInfo[] dir = new DirectoryInfo(#"C:\SomePath").GetDirectories("*.*", SearchOption.AllDirectories);
foreach(DirectoryInfo d in dir)
{
lst.Add(d.Name);
}
This will give you the list of all the folders in your directory.
Use this to get the names of subdirectories in the directory specified by "yourpath". The result is an array of strings.
Directory.GetDirectories("yourpath");
Easy as this:
string[] folders = System.IO.Directory.GetDirectories(#"F:\Unzip\","*", System.IO.SearchOption.AllDirectories);
Reference: http://msdn.microsoft.com/en-us/library/c1sez4sc.aspx
Directory.GetDirectories(#"F:\Unzip") will yield a string[] of full paths to each directory in F:\Unzip
read all directories without foreach loop using lambda
List<string> lst = new List<string>();
var allDir = new DirectoryInfo(#"D:\Github").GetDirectories("*.*", SearchOption.AllDirectories).Select(x=>x.Name).ToList();
lst = allDir;