How to search files from directory using filename? - c#

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

Related

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.

System.IO.File.Delete invalid characters

I'm trying to delete all files in a directory by doing this:
System.IO.File.Delete(directoriodestino_imagenes + #"\*.*");
Where, directoriodestino_imagenes = "C:\\dcm\\patients\\NAME_LASTNAME\\DCM\\".
And I get this:
{"Illegal characters in path."}
Any hints what I may be doing wrong?
It's the wildcard character. You cannot delete multiple files using Delete method. You either need to delete the whole folder (look at the Delete folder method at http://msdn.microsoft.com/en-us/library/fxeahc5f(v=vs.110).aspx) or just remove them one by one. E.g. like in Deleting multiple files with wildcard
Actually it is possible to delete Files in a folder. Here is how I do it.
string directory = #"C:\File Downloader\DownloadedFile\";
string[] file = Directory.GetFiles(directory); // get all files in the folder.
foreach (string fileName in file )
File.Delete(fileName );

retrieve last modified filename from nested directories

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.

Search file

I have to search the filepath from filename into my harddisk.
I was wondering if there is a way to use main Windows 7 search manager (start->edit text with "search programs and file".
Or simply if there is a quick way to find filepath within computer
Can you help me?
You'll need the Windows Search SDK.
Edit: Check out the related MSDN docs.
Here's some sample code, i've used in my univercity project:
DirectoryInfo di = new DirectoryInfo("/some/path");
foreach (FileInfo i in di.GetFiles("filter.text"))
{
// do something
}
Here, /some/path is path where you want to search files and filter.text is filename filter (for example, *.* for all files or *.cpp for .cpp files match. These would match all files or 1.cpp, main.cpp and Main.Project.cpp, respectively).

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