I have a folder path with me something like "c:/videos". it contains subfolders like car, bike, bus ... etc. need to get only the sub folder name and store in a string array.
And please note i don't need a full sub folder path
out needed like:- car, bike, bus
not like c:/videos/car
c:/videos/bike
c:/videos/bus
You have to iterate over the SubDirectories.
And replace the startpath c:\videoswith an empty string:
var rootDir = #"c:\videos";
DirectoryInfo directoryInfo = new DirectoryInfo(rootDir);
var dirs = new System.Collections.Generic.List<string>();
foreach (var dir in directoryInfo.GetDirectories())
{
dirs.Add(dir.Name.Replace($"{rootDir}\\", ""));
}
var result = dirs.ToArray();
You can use GetDirectories method
var directories = Directory.GetDirectories(#"c:/videos");
this will give you a string array of all the subdirectories and then you can call Path.GetDirectoryName() to get the folder name
List<string> subfolders = List<string>();
var directories = Directory.GetDirectories(#"c:/videos");
foreach(var directory in directories)
{
subfolders.Add(Path.GetDirectoryName(directory));
}
var result = subfolders.ToArray();
string yourPath= #"C:\videos";
// Get all subdirectories
string[] subDirs = Directory.GetDirectories(root);
foreach (string subdirectory in subdirectoryEntries)
LoadSubDirs(subdirectory);
List<string> subfolders = List<string>();
private void LoadSubDirs(string dir)
{
subfolders.Add(Path.GetDirectoryName(dir));
string[] subdirectoryEntries = Directory.GetDirectories(dir);
foreach (string subdirectory in subdirectoryEntries)
{
LoadSubDirs(subdirectory);
}
}
Related
I have code that steps through a main directory and all the sub directories. The images in each sub directories needs to be renamed as per the folder it is ins name.
C:\Users\alle\Desktop\BillingCopy\uploaded 27-02\\Batch002-190227010418829\PPA14431564096\File1.png
should rename to
C:\Users\alle\Desktop\BillingCopy\uploaded 27-02\Batch002-190227010418829\PPA14431564096\PPA14431564096.png
I can see the code is stepping through every thing but the image isn't beeing renamed and I can't see where I went wrong
while(isTrue)
{
try
{
//write your code here
string filename1 = "1.tif";
string newFileName = "allen.tif";
string[] rootFolder = Directory.GetDirectories(#"C:\Users\alle\Desktop\BillingCopy");
foreach(string dir in rootFolder)
{
string[] subDir1 = Directory.GetDirectories(dir);
foreach(string subDir in subDir1)
{
string[] batchDirList = Directory.GetDirectories(subDir);
foreach(string batchDir in batchDirList)
{
string[] waybillNumberDir = Directory.GetDirectories(batchDir);
foreach(string hawbDir in waybillNumberDir)
{
string waybillNumber = Path.GetDirectoryName(hawbDir);
string[] getFileimages = Directory.GetFiles(hawbDir);
foreach(string imgInDir in getFileimages)
{
File.Copy(imgInDir, Path.Combine(#"C:\Users\alle\Desktop\Copy", string.Format("{0}.{1}", waybillNumber, Path.GetExtension(imgInDir))));
}
}
}
}
}
File.Copy(Path.Combine("source file", filename1), Path.Combine("dest path",
string.Format("{0}{1}", Path.GetFileNameWithoutExtension(newFileName), Path.GetExtension(newFileName))), true);
}
catch { }
}
When querying you can try using Linq to obtain the required data:
// All *.png files in all subdirectories
string rootDir = #"C:\Users\alle\Desktop\BillingCopy";
var agenda = Directory
.EnumerateFiles(rootDir, "*.png", SearchOption.AllDirectories)
.Select(file => new {
oldName = file,
newName = Path.Combine(
Path.GetDirectoryName(file),
new DirectoryInfo(Path.GetDirectoryName(file)).Name + Path.GetExtension(file))
})
.ToArray();
Then we can move (not copy) the files:
foreach (var item in agenda)
File.Move(item.oldName, item.newName);
I need find the specific file/folder on my hard drive.
For example i need find a file (do1.bat) and then store the path of the file. But i dont know where can it be stored, so i have to scan all hard drive.
How can i use C# for this?
A simple way would be
var results = Directory.GetFiles("c:\\", "do1.bat", SearchOption.AllDirectories);
This would recurse through all directory and collect all files named do1.bat. Unfortunatly this will not work on complete c:\ since it will throw exceptions if you don't have access to a directory, which surely will happen.
So this is a recursive version:
private static void FindFile(DirectoryInfo currentDirectory, string pattern, List<FileInfo> results)
{
try
{
results.AddRange(currentDirectory.GetFiles(pattern, SearchOption.TopDirectoryOnly));
foreach (DirectoryInfo dir in currentDirectory.GetDirectories("*", SearchOption.TopDirectoryOnly).Where(d => d.Name != "." && d.Name != ".."))
FindFile(dir, pattern, results);
}
catch
{
// probably no access to directory
}
}
This recurses through the directory tree and tries to get the files in a directory and then all subdirectories (except . and ..).
You can use it this way:
DirectoryInfo d = new DirectoryInfo("c:\\");
List<FileInfo> results = new List<FileInfo>();
FindFile(d, "do1.bat", results);
This will find all files named do1.bat in any subdirectory of C:\\ and enlist the FileInfos in the results list.
this should provide you a list of files, matching your search pattern
string[] Result = Directory.GetFiles(#"C:\", "do1.bat", SearchOption.AllDirectories);
Refer: https://msdn.microsoft.com/en-us/library/07wt70x2(v=vs.110).aspx
List<string> lstfilepaths = new List<string>();
public static void ProcessDirectory(string targetDirectory)
{
// Process the list of files found in the directory.
string [] fileEntries = Directory.GetFiles(targetDirectory);
foreach(string fileName in fileEntries) // included as per your logic
{
if(fileName == "do1.bat")
{
ProcessFile(fileName);
}
}
// Recurse into subdirectories of this directory.
string [] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach(string subdirectory in subdirectoryEntries)
ProcessDirectory(subdirectory);
}
public static void ProcessFile(string path)
{
lstfilepaths.Add(path);
}
For one file:
public string FindFileByName(string fileName, string searchPath)
{
string resultPath = null;
DirectoryInfo directoryInWhichToSearch = new DirectoryInfo(searchPath);
FileInfo foundFile = directoryInWhichToSearch.GetFiles(fileName, SearchOption.AllDirectories)[0];
resultPath = foundFile.FullName;
return resultPath;
}
You can then use it like this:
string fileFullPath = FindFileByName("do1.bat", #"C:\");
I am new to C# programming.Please suggest me how to retrieve the fullpath but using only file.Name in my code as I only want to enter file name in my listBox not full path
My code is:
listBox1.DataSource = GetFolder("..\\video\\");
private static List<string> GetFolder(string folder)
{
List<string> FileList = new List<string>();
var allFiles = new DirectoryInfo(folder).GetFiles("*.mpg",
SearchOption.AllDirectories)
foreach (FileInfo file in allFiles)
{
FileList.Add(file.FullName);
}
return FileList;
}
FileInfo(path).Directory.FullPath
Your actual problem of your code is missing semi-colon for this line
var allFiles = new DirectoryInfo(folder).GetFiles("*.mpg",
SearchOption.AllDirectories)
It should be
var allFiles = new DirectoryInfo(folder).GetFiles("*.mpg",
SearchOption.AllDirectories);
If I get you right, you want the FullPath as value but only the FileName displayed. To achieve this, you could use a List of FileInfos containing both of these values and tell the ListBox, which member is the value and which one should be displayed:
this.listBox1.DisplayMember = "Name";
this.listBox1.ValueMember = "FullName";
listBox1.DataSource = GetFolder("..\\video\\");
Player.URL = Convert.ToString(listBox1.SelectedValue); // Instead of SelectedItem
private static List<FileInfo> GetFolder(string folder)
{
List<FileInfo> fileList = new List<FileInfo>();
foreach (FileInfo file in new DirectoryInfo(folder).GetFiles("*.mpg", SearchOption.AllDirectories))
{
fileList.Add(file);
}
return fileList;
}
FileList.Add(file.FullName);
Please Change this line like below
FileList.Add(file.Name );
listBox1.DataSource = GetFolder("..\\video\\");
private static List<string> GetFolder(string folder)
{
List<string> FileList = new List<string>();
var allFiles = new DirectoryInfo(folder).GetFiles("*.mpg",
SearchOption.AllDirectories)
foreach (FileInfo file in allFiles)
{
FileList.Add(file.Name);
}
return FileList;
}
Using C# (.NET), how can I search a file system given a directory search mask like this: (?)
\\server\Scanner\images\*Images\*\*_*
For example, I need to first find all top-level directories:
\\server\Scanner\images\Job1Images
\\server\Scanner\images\Job2Images
...then I need to procede further with the search mask:
\\server\Scanner\images\Job1Images\*\*_*
\\server\Scanner\images\Job2Images\*\*_*
This doesn't seem too complicated but I can't figure it out for the life of me...
As mentioned above, I'm using C# and .NET. The search can be trying to locate directories or files. (i.e. *.txt, or <*Directory>)
Like this:
Top Level Directories:
//get Top level
string[] TopLevel = Directory.GetDirectories(path);
And then you will have to do a resursive function of this folders using wildcard pattern,
for example:
// Only get subdirectories that begin with the letter "p."
string pattern = "p*";
string[] dirs = folder.GetDirectories(path, pattern);
I suggest you play with wildcards to get the array output and you will figure out
which is the best way, if using resursive function or directly quering paths.
Edit: Ahh, new functionality with .NET 4 so you don't have to do a recursive function (Thanks Matthew Brubaker)
IEnumerable<String> matchingFilePaths2 = System.IO.Directory.EnumerateFiles(#"C:\some folder to start in", filePatternToMatchOn, System.IO.SearchOption.AllDirectories);
First Answer:
//get all files that have an underscore - searches all folders under the start folder
List<String> matchingFilePaths = new List<string>();
String filePatternToMatchOn = "*_*";
FileUtilities.GetAllFilesMatchingPattern(#"C:\some folder to start in", ref matchingFilePaths, filePatternToMatchOn);
...
public static void GetAllFilesMatchingPattern(String pathToGetFilesIn, ref List<String> fullFilePaths, String searchPattern)
{
//get all files in current directory that match the pattern
String[] filePathsInCurrentDir = Directory.GetFiles(pathToGetFilesIn, searchPattern);
foreach (String fullPath in filePathsInCurrentDir)
{
fullFilePaths.Add(fullPath);
}
//call this method recursively for all directories
String[] directories = Directory.GetDirectories(pathToGetFilesIn);
foreach (String path in directories)
{
GetAllFilesMatchingPattern(path, ref fullFilePaths, searchPattern);
}
}
public static IEnumerable<string> GetImages()
{
//For each "*Image" directory
foreach (var jobFolder in Directory.EnumerateDirectories(#"\\server\Scanner\images", "*Images"))
{
//For each first level subdirectory
foreach (var jobSubFolder in Directory.EnumerateDirectories(jobFolder))
{
//Enumerate each file containing a '_'
foreach (var filePath in Directory.EnumerateFiles(jobSubFolder, "*_*", SearchOption.TopDirectoryOnly))
{
yield return filePath;
}
}
}
}
Only the files from the first level subdirectories of each "*Image" directory are enumerated.
Finally you can use it with:
foreach (var path in GetImages())
{
Console.WriteLine(path);
}
There is a C# procedure where you can search folder by path pattern with wildcards like * and ?.
Example if path pattern C:\Folder?*\Folder2 is passed to the procedru, then a list of folder path will be returned
C:\Folder1\A\Folder2
C:\FolderA\B\Folder2
...
and so on
static List<string> GetFoldersByPathPattern(string folderPathPattern)
{
List<string> directories = new List<string>();
directories.Add("");
string[] folderParts = folderPathPattern.Split(new char[] { '\\' }, StringSplitOptions.None);
foreach (string folderPart in folderParts)
{
if (folderPart.Contains('*') || folderPart.Contains('?'))
{
List<string> newDirectories = new List<string>();
foreach (string directory in directories)
{
foreach (string newDirectory in Directory.GetDirectories(directory, folderPart))
{
newDirectories.Add(newDirectory);
}
}
directories = newDirectories;
}
else
{
for (int i = 0; i < directories.Count(); i++)
{
directories[i] = directories[i] + folderPart + "\\";
}
}
}
return directories;
}
Well I like this nice piece of code right here it seems to work awesomely but I can't seem to add any more directories to it
DirectoryInfo dir = new DirectoryInfo(#"C:\temp");
foreach(FileInfo files in dir.GetFiles())
{
files.Delete();
}
foreach (DirectoryInfo dirs in dir.GetDirectories())
{
dirs.Delete(true);
}
I would also like to add in special folders as well like History and cookies and such how would I go about doing that (I would like to include at least 4-5 different folders)
Perhaps something like this would help. I did not test it.
public void DeleteDirectoryFolders(DirectoryInfo dirInfo){
foreach (DirectoryInfo dirs in dirInfo.GetDirectories())
{
dirs.Delete(true);
}
}
public void DeleteDirectoryFiles(DirectoryInfo dirInfo) {
foreach(FileInfo files in dirInfo.GetFiles())
{
files.Delete();
}
}
public void DeleteDirectoryFilesAndFolders(string dirName) {
DirectoryInfo dir = new DirectoryInfo(dirName);
DeleteDirectoryFiles(dir)
DeleteDirectoryFolders(dir)
}
public void main() {
List<string> DirectoriesToDelete;
DirectoriesToDelete.add("c:\temp");
DirectoriesToDelete.add("c:\temp1");
DirectoriesToDelete.add("c:\temp2");
DirectoriesToDelete.add("c:\temp3");
foreach (string dirName in DirectoriesToDelete) {
DeleteDirectoryFilesAndFolders(dirName);
}
}
Here's a recursive function that will delete all files in a given directory and navigate down the directory structure. A pattern string can be supplied to only work with files of a given extension, as per your comment to another answer.
Action<string,string> fileDeleter = null;
fileDeleter = (directoryPath, pattern) =>
{
string[] files;
if (!string.IsNullOrEmpty(pattern))
files = Directory.GetFiles(directoryPath, pattern);
else
files = Directory.GetFiles(directoryPath);
foreach (string file in files)
{
File.Delete(file);
}
string[] directories = Directory.GetDirectories(directoryPath);
foreach (string dir in directories)
fileDeleter(dir, pattern);
};
string path = #"C:\some_folder\";
fileDeleter(path, "*.bmp");
Directories are otherwise left alone, and this can obviously be used with an array or list of strings to work with multiple initial directory paths.
Here is the same code rewritten as a standard function, also with the recursion as a parameter option.
public void DeleteFilesFromDirectory(string directoryPath, string pattern, bool includeSubdirectories)
{
string[] files;
if (!string.IsNullOrEmpty(pattern))
files = Directory.GetFiles(directoryPath, pattern);
else
files = Directory.GetFiles(directoryPath);
foreach (string file in files)
{
File.Delete(file);
}
if (includeSubdirectories)
{
string[] directories = Directory.GetDirectories(directoryPath);
foreach (string dir in directories)
DeleteFilesFromDirectory(dir, pattern, includeSubdirectories);
}
}