How to get approximate file path? - c#

I have a list file path as follow:
C:\Data\Default.aspx
C:\Data\Global.asax
C:\Data\Web.config
C:\Data\bin\PerlsComWebProject1.dll
C:\Data\bin\PerlsComWebProject1.pdb
I have a method to get file from folder path, however I want to print result as below:
Data\Default
Data\Global
Data\Web.config
Data\bin\PerlsComWebProject1
Data\bin\PerlsComWebProject1
Call: GetFilePathWithOutExtention(#"C:\\Data");
My code is only return file without an extension.
void GetFilePathWithOutExtention(string path)
{
string[] paths = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
foreach(var path in paths)
{
Console.WriteLine(Path.GetFileNameWithoutExtension(path));
}
}
Update: Thanks for your comments. "C:\Data\" is only a sample, sorry so make you confused. Actual, I have a any folder, I want to search this folder, get approximate path: this folder...\filename with out extention.
Ex: I have a path as follow: D:\EHO\Phase1\Data\Document\text.txt,....when I call method: GetFilePathWithOutExtention("D:\EHO\Phase1"), I want to output: Phase1\Data\Document\text, or GetFilePathWithOutExtention("D:\EHO\Phase1\Data"), output: Data\Document\text.
Thanks.

I think what you're looking for is Uri.MakeRelativeUri
So you could do something like this:
var folder = new Uri(#"C:\Data");
var paths = System.IO.Directory.GetFiles(folder.LocalPath, "*.*", System.IO.SearchOption.AllDirectories);
foreach (var uri in paths.Select(p => new Uri(p)))
{
Console.WriteLine(folder.MakeRelativeUri(uri).ToString());
}
This prints
Data/Default.aspx
Data/Global.asax
Data/Web.config
Data/bin/PerlsComWebProject1.dll
Data/bin/PerlsComWebProject1.pdb

A generic answer, valid for all folders inside the machine drives, not only 1st level:
void GetFilePathWithOutExtention(string path)
{
// Get the name of the folder containing your path (for further remove in the items folder)
string parentFolderName = Directory.GetParent(path).FullName;
string[] filePaths = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
foreach(string fileItemPath in filePaths)
{
// Get the current folder without the initial folder path
string currentItemPath = Path.GetDirectoryName(fileItemPath).Remove(0, parentFolderName.Length);
Console.WriteLine(Path.Combine(currentItemPath, Path.GetFileNameWithoutExtension(fileItemPath)));
}
}

you can just Show from the 4th char
void GetFilePathWithOutExtention(string path)
{
string[] filesName = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
foreach(var fileName in filesName)
{
string pathToWrite = Path.GetFileNameWithoutExtension(fileName);
if(pathToWrite != null && pathToWrite.length >3 )
Console.WriteLine(pathToWrite.Substring(3,pathToWrite.length);
}
}

Related

Accessing files within child directories

I am trying to access the files in the images directory that lies within another directory but when I run my code it doesn't print out anything:
string path = #"C:\Path";
DirectoryInfo DFolder = new DirectoryInfo(path);
Collection cDetails = new Collection(DFolder);
string DFPath = DFolder.Name;
DirectoryInfo imDetails = new DirectoryInfo(imPath);
// Get Desired Directories
List<string> directoryFilter = new List<string> {"images", "videos", "RAW"};
List<DirectoryInfo> directoryList = DFolder
.GetDirectories("*", SearchOption.AllDirectories)
.Where(x => directoryFilter.Contains(x.Name.ToLower()))
.ToList();
string dpath = directoryList.ToString();
foreach (DirectoryInfo record in directoryList)
{
foreach (FileInfo file in record.GetFiles(#"*", SearchOption.TopDirectoryOnly))
{
Console.WriteLine(file); //It compiles but doesn't print anything on the console
}
}
Note: This isn't really an answer, so I'll delete it shortly, but wanted to give some sample code to test with in case it helps.
Your code works fine for me, so it seems that the problem is that either the directories don't exist, or they don't contain any files.
Here's a test program you can run which creates a bunch of directories under c:\temp, some of which have the names we care about. The names we care about are also found at different levels of depth in the path, yet they are all discovered:
static void CreateTestPathsAndFiles()
{
// Paths to create for testing. We will put a file in each directory below,
// but our search code should only print the file paths of those files that
// are directly contained in one of our specially-named folders
var testPaths = new List<string>
{
#"c:\temp\dummy1",
#"c:\temp\dummy1\raw", // This should print
#"c:\temp\dummy2",
#"c:\temp\dummy2\extra",
#"c:\temp\dummy3",
#"c:\temp\dummy3\dummy31",
#"c:\temp\dummy3\dummy32\raw", // This should print
#"c:\temp\extra",
#"c:\temp\images", // This should print
#"c:\temp\notUsed",
#"c:\temp\notUsed\videos", // This should print
#"c:\temp\raw", // This should print
#"c:\temp\videos\dummy1",
};
// Just something to make a unique file name
int fileId = 0;
// for testing, ensure that the directories exist and contain some files
foreach(var testPath in testPaths)
{
// Create the directory
Directory.CreateDirectory(testPath);
// Add a file to it
File.CreateText(Path.Combine(testPath, $"TempFile{fileId}.txt"))
.Write($"Dummy text in file {fileId}");
// Increment our file counter
fileId++;
}
}
static void Main(string[] args)
{
// Create our paths and files for testing
CreateTestPathsAndFiles();
// Now set our root directory, search for all folders matching our
// special folder names, and print out the files contained in them
var path = #"C:\Temp";
var directoryFilter = new List<string> {"images", "videos", "raw"};
// Get ALL sub-directories under 'path' whose name is in directoryFilter
var subDirectories = new DirectoryInfo(path)
.GetDirectories("*", SearchOption.AllDirectories)
.Where(x => directoryFilter.Contains(x.Name.ToLower()));
foreach (DirectoryInfo subDir in subDirectories)
{
foreach (FileInfo file in subDir.GetFiles(#"*", SearchOption.TopDirectoryOnly))
{
// We're using the FullName so we see the whole file path in the output
Console.WriteLine(file.FullName);
}
}
GetKeyFromUser("\nDone! Press any key to exit...");
}
Output
Note that the 5 files we expected to find are listed, but no others:
foreach (FileInfo file in record.GetFiles(#"*", SearchOption.TopDirectoryOnly))
{
Console.WriteLine(file); //It compiles but doesn't print anything on the console
}
SearchOption.TopDirectoryOnly will only search files in C://Path/images but not its subfolders.
a possible fix for this is to simply change your 2nd foreach loop to look like this:
foreach (FileInfo file in record.GetFiles(#"*", SearchOption.AllDirectories))
{
Console.WriteLine(file); //It compiles but doesn't print anything on the console
}
Edit:
Using SearchOption.AllDirectories as parameter is supposed to catch all cases of subfolders within your subfolder e.g. something like C://images//dir//somefile.txt instead of only taking the files within the topdirectory(in this case C://images). Which is(as i understood your question) exactly the kind of behaviour you were looking for.
Full code:
{
static void Main(string[] args)
{
// Directory Info
string path = #"C:\Path";
DirectoryInfo DFolder = new DirectoryInfo(path);
string DFPath = DFolder.Name;
// Get Desired Directories
List<string> directoryFilter = new List<string> { "images", "videos", "raw" };
List<DirectoryInfo> directoryList = DFolder.GetDirectories("*", SearchOption.AllDirectories).Where(x => directoryFilter.Contains(x.Name.ToLower())).ToList();
string dpath = directoryList.ToString();
foreach (DirectoryInfo record in directoryList)
{
foreach (FileInfo file in record.GetFiles(#"*", SearchOption.AllDirectories)) //searches directory record and its subdirectories
{
Console.WriteLine(file);
}
}
}
Final Edit: Sample output given the following structure:
C://Path//images//images.somefile.txt
C://Path//images//temp//images.temp.somefile.txt
C://Path//raw//raw.somefile.txt
C://Path//vidoes//videos.somefile.txt

C# How can I get all of subfolder of the current folder path

C# How can I get all of subfolder of the current folder path?. For example, I have a Public folder that is a parent folder. So in Public folder I have Images folder, and in Images folder I have AA, BB, CC,... folder.
May be any recursive here?
P/S: I want to get the result like the tree view:
Public
--Images
----AA
----BB
----CC
It is my understanding that you want to list the subdirectories below a given path that contain only files.
static IEnumerable<string> GetSubdirectoriesContainingOnlyFiles(string path)
{
return from subdirectory in Directory.GetDirectories(path, "*", SearchOption.AllDirectories)
where Directory.GetDirectories(subdirectory).Length == 0
select subdirectory;
}
or You can also use this.
DirectoryInfo dInfo = new DirectoryInfo(<path to dir>);
DirectoryInfo[] subdirs = dInfo.GetDirectories();
Using Microsoft's Ix-Main package:
static IEnumerable<string> EnumerateSubdirs(string path)
{
return EnumerableEx.Expand(
Directory.EnumerateDirectories(path),
subPath => Directory.EnumerateDirectories(subPath));
}
Expand will recursively apply a method to a collection, returning each item breadth-first. So, if you pass in "Public" there, it'll give you:
Public\Images
Public\Images\AA
Public\Images\BB
Public\Images\CC
If you wanted to include the top-level folder, that's plenty easy too:
static IEnumerable<string> EnumerateSubdirs(string path)
{
var subDirs = EnumerableEx.Expand(
Directory.EnumerateDirectories(path),
subPath => Directory.EnumerateDirectories(subPath));
return EnumerableEx.Return(path).Concat(subDirs);
}
Which would result in:
Public
Public\Images
Public\Images\AA
Public\Images\BB
Public\Images\CC
Try This:
String[] dirs= System.IO.Directory.GetDirectories("C:\\");
foreach(string str in dirs)
Console.WriteLine(str);
try this
Dictionary<string, string> dicData = new Dictionary<string, string>();
private void processDirectory(string startLocation)
{
foreach (var directory in Directory.GetDirectories(startLocation))
{
DirectoryInfo dr = new DirectoryInfo(directory);
{
if (!dicData.ContainsKey(dr.Parent.Name))
dicData.Add(dr.Parent.Name, dr.Name);
else
dicData[dr.Parent.Name] += "," + dr.Name;
}
processDirectory(directory);
}
}
A --> B , C
B --> X --> Y -->Z
C --> P --> Q

Searching through a file structure to count items in a subfolder

I am having an issue with trying to make a list by searching through a file structure. Was trying to make a basic c# console program that would just run and do this.
My structure is organize like the following.
My Network \
X1 \
Users \
(many many user folders) \
Search for a specific sub folder \
make a list in a text file of any folders within this sub folder
So i have to be able to search every user folder and then check for a folder (this will be the same every time) Then make a list of the found folders within that sub folder with the following format
username (name of the user folder) >> Name of folder within the specific folder.
its been a terribly long time since i have had to try anything with searching within a file structure so blanking on this terribly.
**************** EDIT!!!!!
Thanks for the info and links. Working on this now but wondering if this makes sense and would work. Don't want to just test it before i make sure it looks like something that wouldn't just screw up.
TextWriter outputText = new StreamWriter(#"C:\FileList.txt", true);
outputText.WriteLine("Starting scan through user folder");
string path = #"\\X1\users";
string subFolder = "^^ DO NOT USE - MY DOCS - BACKUP ^^";
string [] user_folders = Directory.GetDirectories(path);
foreach (var folder in user_folders)
{
string checkDirectory = folder + "\\" + subFolder;
if (Directory.Exists(checkDirectory) == true)
{
string [] inner_folders = Directory.GetDirectories(checkDirectory);
foreach (var folder2 in inner_folders)
{
outputText.WriteLine(folder2);
}
}
}
outputText.WriteLine("Finishing scan through user folder");
outputText.Close();
Fixed and working!!!! had to change the string [] lines, to make it .GetDirectories instead of .GetFiles!!
As Bali C mentioned, the Directory class will be your friend on this one. The following examples should get you started.
From: http://social.msdn.microsoft.com/Forums/en-US/Vsexpressvcs/thread/3ea19b83-b831-4f30-9377-bc1588b94d23/
//Obviously you'll need to define the correct path.
string path = #"My Network\X1\Users\(many many user folders)\Search for a specific sub folder \";
// Will Retrieve count of all files in directry and sub directries
int fileCount = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Length;
// Will Retrieve count of all files in directry but not sub directries
int fileCount = Directory.GetFiles(path, "*.*", SearchOption.TopDirectory).Length;
// Will Retrieve count of files .txt extensions in directry and sub directries
int fileCount = Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories).Length;
If you need to search the /Users/ folder for certain people, or certain conditions you could do the following:
string path = #"PATH_TO_USERS_DIRECTORY";
string [] user_folders = Directory.GetFiles(path);
foreach(var folder in user_folders)
{
if folder == "MyFolder";
Process(folder); //Search the directory here.
}
Try the following implementation. This will just write to the console:
const string root = "<<your root path>>";
const string directoryToLookFor = "<<the folder name you are looking for>>";
foreach (var directory in Directory.EnumerateDirectories(root, "*.*", SearchOption.TopDirectoryOnly))
{
var foundDirectory = Directory.EnumerateDirectories(directory, directoryToLookFor, SearchOption.TopDirectoryOnly).FirstOrDefault();
if (!String.IsNullOrEmpty(foundDirectory))
{
var filesInside = Directory.GetFiles(foundDirectory);
foreach (var file in filesInside)
{
Console.WriteLine(file);
}
}
}
Or you could just do:
foreach (var foundDirectory in Directory.EnumerateDirectories(root, directoryToLookFor, SearchOption.AllDirectories))
{
var filesInside = Directory.GetFiles(foundDirectory);
foreach (var file in filesInside)
{
Console.WriteLine(file);
}
}
Which would search within all subdirectories without you having to iterate over the users' folders.

c# recursive search to check for a file extension

I want to check if a file in the directory I pass has a specific extension.
public static bool ProcessDirectory(string targetDirectory)
{
// Process the list of files found in the directory.
string[] fileEntries = System.IO.Directory.GetFiles(targetDirectory);
foreach (string fileName in fileEntries)
if (System.IO.Path.GetExtension(fileName).ToLower().Contains(pattern))
return true;
// Recurse into subdirectories of this directory.
string[] subdirectoryEntries = System.IO.Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries)
return ProcessDirectory(subdirectory);
return false;
}
call from:
bool foundPattern = false;
//recursive search - based on search pattern
if (System.IO.File.Exists(myDirectory) && System.IO.Path.GetExtension(myDirectory).Contains(pattern))
{
// This path is a file
foundPattern = true;
}
else if (System.IO.Directory.Exists(myDirectory))
{
// This path is a directory
foundPattern = ProcessDirectory(myDirectory);
}
The thing is, I don't get some results (I get false even when there are files with extension .xzz, assuming that I ask for extension .x in the search pattern - sometimes I get true, sometimes I get false).
If I step through it looks like I am looking at directories and going into them recursively and going through files...
But it doesn't.
What you want to do can be easily be done with this
string path = #"C:\temp\";
string extension = "*.txt";
var files = Directory.GetFiles(path, extension);
//or recursivly
var files = Directory.GetFiles(path, extension, SearchOption.AllDirectories);
In your case:
public static bool ProcessDirectory(string startPath, string pattern)
{
return Directory.GetFiles(startPath, pattern, SearchOption.AllDirectories).Any();
}
I think there's a bug in your code:
// Recurse into subdirectories of this directory.
string[] subdirectoryEntries = System.IO.Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries)
return ProcessDirectory(subdirectory);
Should be something like:
// Recurse into subdirectories of this directory.
string[] subdirectoryEntries = System.IO.Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries)
if (ProcessDirectory(subdirectory))
return true;
Otherwise you're only returning the results for a single subdirectory.
It's the same kind of loop you have in the beginning of your function. You do it right the first time.

Directory is not reading properly

I am having One Directory
C:\Kuldeep\kverma\kver\
After that It consists thousands of Folders with Different name .Each Folder consists Different Excel File . I need to read Each Files from Different Folders .
I want To read All The Folders Path from C:\Kuldeep\kverma\kver\ Folder.
I used below code for getting the folders name with path ..
string path = #"C:\Kuldeep\kverma\kver\";
DirectoryInfo dir = new DirectoryInfo(path);
Console.WriteLine("File Name Size Creation Date and Time");
Console.WriteLine("========");
foreach (DirectoryInfo dirinfo in dir.GetDirectories())
{
String name = dirinfo.Name;
String pth = dirinfo.FullName;
Console.WriteLine( name, pth);
}
Total 10700 folders are there in C:\Kuldeep\kverma\kver\ Directory But It is reading only 54 Folder..
Please provide me any solution for Reading Folder name and location Also Reading File from Each Folder in Single Shot .
You should put a try catch around the GetDirectories call to handle the exceptions in the below post.
That might give you a clue as to why it is not enumerating properly.
http://msdn.microsoft.com/en-us/library/c1sez4sc.aspx
Try a recursive approach:
namespace ConsoleApplication1
{
using System;
using System.Collections.Generic;
using System.IO;
class Program
{
public static IList<DirectoryInfo> dirs;
static void Main(string[] args)
{
dirs = new List<DirectoryInfo>();
var dir = new DirectoryInfo(#"c:\tmp");
GetDirs(dir);
Console.WriteLine(dirs.Count);
}
public static void GetDirs(DirectoryInfo root)
{
foreach (var directoryInfo in root.GetDirectories())
{
dirs.Add(directoryInfo);
GetDirs(directoryInfo);
}
}
}
}
Now I'm not sure what hidden dangers might be lurking because of this (Stack overflow exceptions, access denied?) so I'd recommend placing a try..catch block in the foreach loop to help you out.
If you want to view the contents of every sub directory:
// Flatten out the directory structure in to a string array.
var directoryList = Directory.GetDirectories("<<RootPath>>", "*", SearchOption.AllDirectories);
foreach (var directory in directoryList)
{
DirectoryInfo info = new DirectoryInfo(directory);
}
edited with the questions code updated:
string path = #"C:\Kuldeep\kverma\kver\";
string[] directoryArray = Directory.GetDirectories(path, "*", SearchOption.AllDirectories);
foreach (var directory in directoryArray)
{
DirectoryInfo dirinfo = new DirectoryInfo(directory);
String name = dirinfo.Name;
String pth = dirinfo.FullName;
Console.WriteLine(name, pth);
}

Categories