retrieve last modified filename from nested directories - c#

I have a root directory and inside that further directories are there. These directories contains various Html and ncx files. I have to get the name of the file that has been last modified.
I am using this code
string filePath = #"~\FolderName\";
string completeFilePath = Server.MapPath(filePath);
var directory = new DirectoryInfo(completeFilePath);
var fileName = (from f in directory.GetFiles()
orderby f.LastWriteTime descending
select f).First();
lblDisplayFileName.Text=fileName.ToString();
But it is only searching files that are placed only in root directory. It is not searching files that are present further in directories of root directory. I don't know how to get last modified filename of the files that are present further in nested directories. I have to display the name of file that has been last modified from all of the files irrespective of present in any directory.

Have a look at the documentation of DirectoryInfo.GetFiles:
MSDN:
Returns a file list from the current directory.
You have to use the overload that takes a SearchOption:
directory.GetFiles("*.*", SearchOption.AllDirectories)

Try the overload of GetFiles which takes 2 parameters
from f in directory.GetFiles(".", SearchOption.AllDirectories)
SearchOption specifies whether the search operation should include only the current directory or all subdirectories.

Related

Is there a way to get a list of paths in a folder excluding specific folders

I am trying to write a program that "automatically" creates a .gitignore file.
What I am trying to achieve is to get a list of paths from a specific folder where specific files (extensions) are excluding specific folders.
Let's say I want to find all groovy file paths in a folder (D://Files) and all subfolders (D://Files/SubFiles) but not the subfolder (D://Files/GroovyBackups).
This is what I have so far.
if (foldersToIgnore.Count == 0)
folders = Directory.EnumerateFiles(targetFolderPath, "*", SearchOption.AllDirectories).ToList();
else
{
folders = Directory.EnumerateFiles(targetFolderPath, "*", SearchOption.AllDirectories)
.Where(
dir =>
!foldersToIgnore.Contains(dir)
)
.ToList();
}
I think the first if statement works fine but as soon as I have folders I want to "ignore" it doesn't
EnumerateFiles returns only file paths, not directories.
You need to check the directory of each file:
var files = Directory.EnumerateFiles(targetFolderPath, "*", SearchOption.AllDirectories)
.Where(filePath => !foldersToIgnore.Contains(new FileInfo(filePath).Directory.Name));
And you can use case insensitive searching by using a StringComparer, for example:
!foldersToIgnore.Contains(new FileInfo(filePath).Directory.Name,
StringComparer.OrdinalIgnoreCase);

Iterate and print all of the file paths of all pdf files in a specific directory using Directory.EnumerateFiles

How can I iterate and print all of the file paths of all .pdf files in a specific directory when using Directory.EnumerateFiles?
The following code only returns the path of the first .pdf file in the specified directory.
IEnumerable<string> files = Directory.EnumerateFiles(#"C:\MyFolder", "*.pdf*", SearchOption.AllDirectories);
foreach (string file in files) {
Console.WriteLine("File Path:{0}", file);
}
// Returns:
// C:\MyFolder\firstPdfFile.pdf
Again, what I want is to be able to print all of the paths of all pdfs files in a specified directory. What am I missing?
EDIT: I'm not getting any errors, but the only thing I see in the console is the path of the first pdf found in the specified directory and I was expecting to see the path of all pdf files in that directory.
haven't used function you written, but suggest you to try out below
string[] filePaths = Directory.GetFiles(#"c:\MyFolder\", "*.pdf",
SearchOption.AllDirectories);
// returns:
// "c:\MyFolder\fist.pdf"
// "c:\MyFolder\subdirectory\sss.pdf"

How to search files from directory using filename?

I have a file name say 'abc' in folder C:\Demo\output. Now i have another folder C:\Demo\base contaning abc.xml and abc.xsd . Using file name 'abc' how to ensure whether file in another folder exist with both extensions?
You should use Directory.GetFiles() with search pattern.
Here is a small example:
string[] dirs = Directory.GetFiles(#"C:\Demo\base ", "abc.*");
More information you can find on MSDN
Try
Directory.GetFiles(RootPath, "abc.*", SearchOption.AllDirectories);
more info here

How to get a file full path in c# with Path.GetFullPath

I am trying to get the full path a file by its name only.
I have tried to use :
string fullPath = Path.GetFullPath("excelTest");
but it returns me an incorrect path (something with my project path).
I have read somewhere here a comment which says to do the following:
var dir = Environment.SpecialFolder.ProgramFilesX86;
var path = Path.Combine(dir.ToString(), "excelTest.csv");
but I do not know where the file is saved , therefore I do not know its environment.
can someone help me how to get the full path of a file only by its name?
The first snippet (with Path.GetFullPath) does exactly what you want. It returns something with your project path because the program EXE file is located in the project\Bin\Debug path, which is therefore the "current directory".
If you want to search for a file on a drive, you can use Directory.GetFiles, which will recursively search for a file in a directory given a name pattern.
This returns all xml-files recursively :
var allFiles = Directory.GetFiles(path, "*.xml", SearchOption.AllDirectories);
http://msdn.microsoft.com/en-us/library/ms143316%28v=vs.100%29.aspx
http://msdn.microsoft.com/en-us/library/ms143448.aspx#Y252
https://stackoverflow.com/a/9830162/2196124
I guess you're trying to find file (like in windows search), right ?
I'd look into this question - you will find all files that has that string in their filename, and from there you can return full filepath.
var fileList = new DirectoryInfo(#"c:\").GetFiles("*excelTest*", SearchOption.AllDirectories);
And then just use foreach to do you manipulations, e.g.
foreach(string file in fileList)
{
// MessageBox.Show(file);
}
What you're looking for is Directory.GetFiles(), you can read up on it here. The gist of it is, you'll pass in the file path and the file name, and you'll get a string array back. In this instance, you can assume top level with C:\. It should be noted, that if nothing is found, the string array will be empty.
You have passed a relative file name to Path.GetFullPath. Microsoft documentation states:
If path is a relative path, GetFullPath returns a fully qualified path that can be based on the current drive and current directory. The current drive and current directory can change at any time as an application executes. As a result, the path returned by this overload cannot be determined in advance.
You cannot get the same full path name from a relative path unless your current directory is the same each time you invoke the function.

Is there a way to find a file by just its name in C#?

We use absolut path or relatvie path to find a file in our C# application right now. Is there a way to find the file just by its name if the file is under the currect working directory or under one of the "paths"?
Use absolute pathe is not good and use relative path is not good enough because we may change project structure by rename or move project folders. If we our code can automatically search current working directory, its subfolders and search system path, that will be more flexible.
thanks,
You can easily build a recursive function to do this for you. Look at Directory.GetDirectories and Directory.GetFiles, both under System.IO
Try this:
string target = "yourFilenameToMatch";
string current = Directory.GetCurrentDirectory();
// 1. check subtree from current directory
matches=Directory.GetFiles(current, target, SearchOption.AllDirectories);
if (matches.Length>0)
return matches[0];
// 2. check system path
string systemPath = Environment.GetEnvironmentVariable("PATH");
char[] split = new char[] {";"};
foreach (string nextDir in systemPath.Split(split))
{
if (File.Exists(nextDir + '\\' + target)
{
return nextDir;
}
}
return String.Empty;
You could call Directory.GetFiles for each root folder in which you want to search for the file. the parameter searchOption allow you to specify whether the search operation look in all subdirectories or only the directory specified. E.g:
public string GetFileName(string[] folders,string fileName) {
string[] filePaths;
foreach(var folder in folders) {
filePaths=Directory.GetFiles(folder,fileName,SearchOption.AllDirectories)
if (filePaths.Lenght>0)
return filePaths[0];
}
}
Try this:
Directory.EnumerateFiles(pathInWhichToSearch, fileNameToFind, SearchOption.AllDirectories);
And, you need to use:
using System.IO;
on top of your class.
This searches all subdirectories of pathInWhichToSearch for a file with name fileNameToFind (it can be a pattern too - like *.txt) and returns result as IEnumerable<string> with full paths of found files.
You can get the exe's directory using
Path.GetDirectoryName(Application.ExecutablePath);
Example Code: http://www.csharp-examples.net/get-application-directory/
And then, you can search the folders from there using recursion. This is a good article on recursive searching for files:
http://support.microsoft.com/kb/303974

Categories

Resources