I have an application that needs to return the names of subdirectories in a specific path. However, the path can include a variable, and towards the end of the path, I want it to check a certain folder.
My current code is something like
string path = "\\\\" + computerList + "\\C$\\Program Files (x86)\\blah1\\blah2\\";
string searchPattern = "*_*";
DirectoryInfo di = new DirectoryInfo(path);
DirectoryInfo[] directories =
di.GetDirectories(searchPattern, SearchOption.AllDirectories);
followed by
foreach (DirectoryInfo dir in directories)
{
versionInformation.Add(computerList+" "+dir.Parent.Parent.Parent+" "+dir.Parent + " " + dir.Name);
}
What I want it to do is take the results from the directory search - and then add \\working\\products\\ and iterate through that full list/path.
So - in short - I want the versionInformation list to end up being
Directory information up to blah2\ - I want it to find the folder after blah2 (which it does) but then I want to append the \\working\\products\\ and use that entire path for what it ends up searching for the *_* in.
EDIT I just realized that I may have been addressing this the wrong way - It appears that my current code actually works - But when it lists the directory names, for some reason, It comes out wrong...
foreach (DirectoryInfo dir in directories)
{
//DirectoryInfo threeLevelsUp = dir.Parent.Parent.Parent;
versionInformation.Add(computerList+" "+dir.Parent.Parent.Parent+" "+dir.Parent + " " + dir.Name);
//Console.WriteLine(dir.Parent + " " + dir.Name);
}
var beautifyList = string.Join(Environment.NewLine, versionInformation);
MessageBox.Show(beautifyList);
The first iteration for (using the below folders as an example) ICanBeDifferent will result in the FIRST item found being labeled as "ICanBeDifferent", but the SECOND result (for something found under ICanBeDifferent) would return FunTimes as the parent.parent.parent.
What could be causing this?!
Example Folders
C:\Program Files (x86)\LLL\Funtimes\ICanBeDifferent\Working\Products\Superman\2015_2_0_7
C:\Program Files (x86)\LLL\Funtimes\ICanBeDifferent\Working\Products\Office\2015_2_2_43
C:\Program Files (x86)\LLL\Funtimes\ThisIsWhatChanges\Working\Products\Lanyard\2015_2_0_70
To me it seems like you want the Path.Combine() method and use it like
string resultDir = Path.Combine(dir, "..\\working\\products");
if dir is a string or
string resultDir = Path.Combine(dir.FullName, "..\\working\\products");
if dir is a DirectoryInfo.
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'd like to browse a directory and get all files with their sizes , names and urls.
I did like this :
int i = 0;
foreach (string sFileName in Directory.GetFiles(Path.Combine(#"C:\Projets", path2)))
{
i++;
}
i count the number of files in a directory but the problem when i have other directories inside it , how can i do to get all files and it caracteristics?
This is a duplicate of many other similar questions. If you want to get extended file info, use the XxxInfo classes, eg DirectoryInfo, FileInfo instead of the Directory and File classes.
Additionally, all GetXXX or EnumerateXXX methods have overloads with the SearchOption parameter which allows you to return all files,not just the files of the top directory.
For your specific question, to get info on all files below a directory using e.g. GetFiles:
var di=new DirectoryInfo(somePath);
var allFiles=di.GetFiles("*",SearchOption.AllDirectories);
foreach(var file in allFiles)
{
Console.WriteLine("{0} {1}",file.Name,file.Length);
}
The difference between GetFiles and EnumerateFiles is that GetFiles returns only after it retrieves all files below a directory, which can take a long time. EnumerateFiles returns an iterator so you can use it in a foreach statement to process each file at a time and stop the iteration if you like by breaking out of the loop.
This should loop through all of the files recursively
foreach (string sFileName in Directory.EnumerateFiles(Path.Combine(#"C:\Projets", path2), "*.*", SearchOption.AllDirectories))
{
//Get file information here
FileInfo f = new FileInfo(sFileName);
Console.WriteLine("{0} - {1}", f.Length, f.Name);
}
I need to read a text file that I know its full path, except one folder's name. I' d use
string readText = File.ReadAllText(path + "\\" + unknownFolderName + "\\" + itemName);
but first, I need to find out unknownFolderName to reach the file' s full path. There is exactly one folder under path, all I need to do is entering under this folder, without knowing its name. How can I achieve this in simplest way?
You could try using Directory.GetDirectories(). If you're guaranteed to only have one folder underneath that folder, then you should be able to do it VIA:
string unknownPath = Directory.GetDirectories(path)[0];
//Now instead of this: [ string readText = File.ReadAllText(path + "\\" + unknownFolderName + "\\" + itemName) ], do this:
string readText = File.ReadAllText(unknownPath + "\\" + itemName);
That should do it. Let me know if it works out for you!
You could use Directory.GetDirectories static method (documentation) which returns the array of strings - full paths to the direcotries in the path you passed to the method. So try something like this (if you are sure that there is at least one directory and you want to use the first one):
string readText = File.ReadAllText(Directory.GetDirectories(path)[0] + "\\" + itemName);
In case you have more than one folder, and you don't know which one is:
Take a look at the following example. You're looking for Windows in the following path: C:\_____\System32\notepad.exe
string path = #"C:\";
var itemName = #"System32\notepad.exe";
var directories = Directory.GetDirectories(path);
foreach (var dir in directories) {
string fullPath = Path.Combine(dir, itemName);
//If you found the correct directory!
if (File.Exists(fullPath)) {
Console.WriteLine(fullPath);
}
}
Use this to get the folder names under your directory:
http://www.developerfusion.com/code/4359/listing-files-folders-in-a-directory/
I accidentally ended up with a bunch of my directories getting borked, what should be:
/myroot/mydirectory
ended up as:
/myroot/mydirecotry/mydirectory/mydirectory
Then nesting could be any where from 1 to N times - I need to find the furthest out /mydirectory and copy all of those files back to the root and kill the duped ones. How do I find the one that is furthest out?
string[] dirs;
string actualDir = #"\myroot\";
string subdir = "mydirectory";
do
{
dirs = System.IO.Directory.GetDirectories(actualDir, subdir);
actualDir += subdir + #"\";
}
while (dirs.Length > 0);
string theLongestPath = actualDir; // The path to the furthest dir
This gets all directories in actualDir that contains subdir, until it's the last one (no other subdirectories containing subdir). If you have any questions on how it works, ask in a comment. And yeah, I've tried it, it really works.
I have a directory that contains jpg,tif,pdf,doc and xls. The client DB conly contains the file names without extension. My app has to pick up the file and upload the file. One of the properties of the upload object is the file extension.
Is there a way of getting file extension if all i have is the path and name
eg:
C:\temp\somepicture.jpg is the file and the information i have through db is
c:\temp\somepicture
Use Directory.GetFiles(fileName + ".*"). If it returns just one file, then you find the file you need. If it returns more than one, you have to choose which to upload.
Something like this maybe:
DirectoryInfo D = new DirectoryInfo(path);
foreach (FileInfo fi in D.GetFiles())
{
if (Path.GetFileNameWithoutExtension(fi.FullName) == whatever)
// do something
}
You could obtain a list of all of the files with that name, regardless of extension:
public string[] GetFileExtensions(string path)
{
System.IO.DirectoryInfo directory =
new System.IO.DirectoryInfo(System.IO.Path.GetDirectoryName(path));
return directory.GetFiles(
System.IO.Path.GetFileNameWithoutExtension(path) + ".*")
.Select(f => f.Extension).ToArray();
}
Obviously, if you have no other information and there are 2 files with the same name and different extensions, you can't do anything (e.g. there is somepicture.jpg and somepicture.png at the same time).
On the other hand, usually that won't be the case so you can simply use a search pattern (e.g. somepicture.*) to find the one and only (if you're lucky) file.
Search for files named somepicture.* in that folder, and upload any that matches ?
Get the lowest level folder for each path. For your example, you would have:
'c:\temp\'
Then find any files that start with your filename in that folder, in this case:
'somepicture'
Finally, grab the extension off the matching filename. If you have duplicates, you would have to handle that in a unique way.
You would have to use System.IO.Directory.GetFiles() and iterate through all the filenames. You will run into issues when you have a collision like somefile.jpg and somefile.tif.
Sounds like you have bigger issues than just this and you may want to make an argument to store the file extension in your database as well to remove the ambiguity.
you could do something like this perhaps....
DirectoryInfo di = new DirectoryInfo("c:/temp/");
FileInfo[] rgFiles = di.GetFiles("somepicture.*");
foreach (FileInfo fi in rgFiles)
{
if(fi.Name.Contains("."))
{
string name = fi.Name.Split('.')[0].ToString();
string ext = fi.Name.Split('.')[1].ToString();
System.Console.WriteLine("Extension is: " + ext);
}
}
One more, with the assumption of no files with same name but different extension.
string[] files = Directory.GetFiles(#"c:\temp", #"testasdadsadsas.*");
if (files.Length >= 1)
{
string fullFilenameAndPath = files[0];
Console.WriteLine(fullFilenameAndPath);
}
From the crippled file path you can get the directory path and the file name:
string path = Path.GetDirectoryName(filename);
string name = Path.GetFileName(filename);
Then you can get all files that matches the file name with any extension:
FileInfo[] found = new DirectoryInfo(path).GetFiles(name + ".*");
If the array contains one item, you have your match. If there is more than one item, you have to decide which one to use, or what to do with them.
All the pieces are here in the existing answers, but just trying to unify them into one answer for you - given the "guaranteed unique" declaration you're working with, you can toss in a FirstOrDefault since you don't need to worry about choosing among multiple potential matches.
static void Main(string[] args)
{
var match = FindMatch(args[0]);
Console.WriteLine("Best match for {0} is {1}", args[0], match ?? "[None found]");
}
private static string FindMatch(string pathAndFilename)
{
return FindMatch(Path.GetDirectoryName(pathAndFilename), Path.GetFileNameWithoutExtension(pathAndFilename));
}
private static string FindMatch(string path, string filename)
{
return Directory.GetFiles(path, filename + ".*").FirstOrDefault();
}
Output:
> ConsoleApplication10 c:\temp\bogus
Best match for c:\temp\bogus is [None found]
> ConsoleApplication10 c:\temp\7z465
Best match for c:\temp\7z465 is c:\temp\7z465.msi
> ConsoleApplication10 c:\temp\boot
Best match for c:\temp\boot is c:\temp\boot.wim