How to find the file by its partial name? - c#

How can I get the full filename?
For example:
I have a file named 171_s.jpg that is stored on the hard disc.
I need to find the file by its partial name, i.e. 171_s, and get the full name.
How can I implement this?

Here's an example using GetFiles():
static void Main(string[] args)
{
string partialName = "171_s";
DirectoryInfo hdDirectoryInWhichToSearch = new DirectoryInfo(#"c:\");
FileInfo[] filesInDir = hdDirectoryInWhichToSearch.GetFiles("*" + partialName + "*.*");
foreach (FileInfo foundFile in filesInDir)
{
string fullName = foundFile.FullName;
Console.WriteLine(fullName);
}
}

Update - Jakub answer is more efficient way to do.
ie, use System.IO.Directory.GetFiles()
http://msdn.microsoft.com/en-us/library/ms143316.aspx
The answer has been already posted, however for an easy understanding here is the code
string folderPath = #"C:/Temp/";
DirectoryInfo dir= new DirectoryInfo(folderPath);
FileInfo[] files = dir.GetFiles("171_s*", SearchOption.TopDirectoryOnly);
foreach (var item in files)
{
// do something here
}

You could use System.IO.Directory.GetFiles()
http://msdn.microsoft.com/en-us/library/ms143316.aspx
public static string[] GetFiles(
string path,
string searchPattern,
SearchOption searchOption
)
path
Type: System.String
The directory to search.
searchPattern
Type: System.String
The search string to match against the names of files in path. The parameter cannot end in two periods ("..") or contain two periods
("..") followed by DirectorySeparatorChar or
AltDirectorySeparatorChar, nor can it contain any of the characters in
InvalidPathChars.
searchOption
Type: System.IO.SearchOption
One of the SearchOption values that specifies whether the search operation should include all subdirectories or only the current
directory.

You can do it like this:
....
List<string> _filesNames;
foreach(var file in _directory)
{
string name = GetFileName(file);
if(name.IndexOf(_partialFileName) > 0)
{
_fileNames.Add(name);
}
}
....

Simple as that:
string path = #"C:\example\directory";
string searchPattern = "*171_s*";
string[] filePaths = Directory.GetFiles(path, searchPattern,SearchOption.AllDirectories);

Related

How to create a folder out of the first few letters of a filename?

So I checked out the basic things but I'd like to do the following:
I have 5 files let's say: X1_word_date.pdf, XX1_word_date.pdf, etc...
I'd like to create a folder structure like: C:\PATH\X1, C:\PATH\XX1, etc...
So how do I take the first letters before the '_' in the file names and put it into a string?
My idea is that I use the Directory.CreateDirectory and than combine the main path and the strings so I get the folders.
How do I do that? Help appreciated.
string fileName = "X1_word_date.pdf";
string[] tokens = fileName.Split('_');
string myPath = "C:\\PATH\\";
Directory.CreateDirectory( myPath + tokens[0]);
Something like this should work. Using Split() will also allow for numbers greater than 9 to be dealt with
Supposed that your files is a List<string> which contains the file name (X2_word_date.pdf,...)
files.ForEach(f => {
var pathName= f.Split('_').FirstOrDefault();
if(!string.IsNullOrEmpty(pathName))
{
var directoryInfo = DirectoryInfo(Path.Combine(#"C:\PATH", pathName));
if(!directoryInfo.Exists)
directoryInfo.Create();
//Then move this current file to the directory created, by FileInfo and Move method
}
})
With simple string methods like Split and the System.IO.Path class:
var filesAndFolders = files
.Select(fn => new
{
File = fn,
Dir = Path.Combine(#"C:\PATH", Path.GetFileNameWithoutExtension(fn).Split('_')[0].Trim())
});
If you want to create that folder and add the file:
foreach (var x in filesAndFolders)
{
Directory.CreateDirectory(x.Dir); // will only create it if it doesn't exist yet
string newFileName = Path.Combine(x.Dir, x.File);
// we don't know the old path of the file so i can't show how to move
}
Or using regex
string mainPath = #"C:\PATH";
string[] filenames = new string[] { "X1_word_date.pdf", "X2_word_date.pdf" };
foreach (string filename in filenames)
{
Match foldernameMatch = Regex.Match(filename, "^[^_]+");
if (foldernameMatch.Success)
Directory.CreateDirectory(Path.Combine(mainPath, foldernameMatch.Value));
}
Using the bigger picture starting with only your Source and Destination directory.
We can list all files we need to move with Directory.GetFiles.
In this list We first isolate the filename with GetFileName.
Using simple String.Split you have the new directory name.
Directory.CreateDirectory will create directories unless they already exist.
To move the file we need its destination path, a combinaison of the Destination directory path and the fileName.
string sourceDirectory = #"";
string destDirectory = #"";
string[] filesToMove = Directory.GetFiles(sourceDirectory);
foreach (var filePath in filesToMove) {
var fileName = Path.GetFileName(filePath);
var dirPath = Path.Combine(destDirectory, fileName.Split('_')[0]);
var fileNewPath= Path.Combine(dirPath,fileName);
Directory.CreateDirectory(dirPath);// If it exist it does nothing.
File.Move(filePath, fileNewPath);
}

C# FileInfo Array to String Array

I have an array that stores files from a directory:
string pathToDirectory = #"C:\files";
System.IO.DirectoryInfo diDir = new DirectoryInfo(pathToDirectory);
System.IO.FileInfo[] File_Array = diDir.GetFiles();
foreach (FileInfo lfileInfo in File_Array)
{
}
I want to try and convert this array into a string type array instead of a FileInfo type. Please let me know how I can go about doing this. Any help would be greatly appreciated.
Use static Directory class instead. It returns files as strings instead of instantiating FileInfo instances which you don't need
string[] files = Directory.GetFiles(pathToDirectory);
If you want just file names without path, then use Path to get rid of directory path:
var fileNames = Directory.GetFiles(pathToDirectory)
.Select(Path.GetFileName);
string[] fileNames = File_Array.Select(f => f.Name).ToArray();

changing absolute Path to relative Path

How i would like to change my absolute Path to relative Path.
anyone can help?
this is my Code
string activeDirectory = #"X:\Temp\";
string[] files = Directory.GetFiles(activeDirectory);
foreach (string fileName in files)
{
.....
}
I would prefer files.Select(f => f.Substring(activeDirectory.Length)).
That means 'Skip x chars and return the rest'.

how to get specific file names using c#

I have 10 zip files in a folder having path like this
TargetDirectory = "C:\docs\folder\"
some of the zip files names are like this
abc-19870908.Zip
abc-19870908.zip
abc-12345678.zip
and some are like this...
doc.zip
doc123.zip
..
I am getting all file names by using following code...
string [] fileEntries = Directory.GetFiles(targetDirectory);
foreach(string fileName in fileEntries)
{
// here I need to compare ,
// I mean I want to get only these files which are having
// these type of filenames `abc-19870908.Zip`
if (filename == "")
{
// I want to do something
}
}
What i have to put in the double quotes in this line if(filename == "") to get like abc-19870908.Zip these filenames.
Would any one please suggest any idea about this?
Many thanks...
If you're only interested in zip files containing a dash, you can provide a search pattern to Directory.GetFiles.
string [] fileEntries = Directory.GetFiles(targetDirectory, "*-*.zip");
Check out this link for more information on those search patterns: http://msdn.microsoft.com/en-us/library/wz42302f.aspx
I guess you can do
if (filename.Contains("-"))
{
...
}
if the - is always present in the filenames you are interested in
or
if (filename.StartsWith("abc-"))
{
...
}
if the filenames always start with abc- for the ones you are interested in.
you can do if(filename.StartsWith ("abc-") ) or you can do if (filename.Contains ( "-" ) ) or you can do string [] fileEntries = Directory.GetFiles(targetDirectory, "abc-*.Zip");
// Consider using this overload:
// public static string[] GetFiles( string path, string searchPattern)
string [] fileEntries = Directory.GetFiles(targetDirectory, "abc*.zip");
Alternatively, you can use a regular expression as follows:
string [] fileEntries = Directory.GetFiles(targetDirectory);
foreach(string fileName in fileEntries)
{
if(Regex.Match (filename, #"abc.*?\.zip", RegexOptions.IgnoreCase))
{
// i want to do something
}
}
List<String> files = Directory.GetFiles(#"C:\docs\folder\").ToList();
var g = from String s in files where s.StartsWith("abc") select s;
foreach(var z in g)
{
//Do stuff in here as a replacement for your if
}
You could use a regular expression that matches your filenames, something along thees lines:
string sPattern = "abc-\d+\.zip";
string [] fileEntries = Directory.GetFiles(targetDirectory);
foreach(string fileName in fileEntries)
{
// here i need to compare , i mean i want to get only these files which are having these type of filenames `abc-19870908.Zip`
if(System.Text.RegularExpressions.Regex.IsMatch(filename , sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
{
// i want to do something
}
}
The regular expression "abc-\d+.zip" means
the string "abc-" followed by any number of digits, followed by a . followed by the string "zip" (regular expression syntax)

Recursively looping through a drive and replacing illegal characters

I have to create an app that drills into a specific drive, reads all file names and replaces illegal SharePoint characters with underscores.
The illegal characters I am referring to are: ~ # % & * {} / \ | : <> ? - ""
Can someone provide either a link to code or code itself on how to do this? I am VERY new to C# and need all the help i can possibly get. I have researched code on recursively drilling through a drive but i am not sure how to put the character replace and the recursive looping together. Please help!
The advice for removing illegal characters is here:
How to remove illegal characters from path and filenames?
You just have to change the character set to your set of characters that you want to remove.
If you have figured out how to recurse the folders, you can get all of the files in each folder with:
var files = System.IO.Directory.EnumerateFiles(currentPath);
and then
foreach (string file in files)
{
System.IO.File.Move(file, ConvertFileName(file));
}
The ConvertFileName method you will write to accept a filename as a string, and return a filename stripped of the bad characters.
Note that, if you are using .NET 3.5, GetFiles() works too. According to MSDN:
The EnumerateFiles and GetFiles
methods differ as follows: When you
use EnumerateFiles, you can start
enumerating the collection of names
before the whole collection is
returned; when you use GetFiles, you
must wait for the whole array of names
to be returned before you can access
the array. Therefore, when you are
working with many files and
directories, EnumerateFiles can be
more efficient.
How to recursively list directories
string path = #"c:\dev";
string searchPattern = "*.*";
string[] dirNameArray = Directory.GetDirectories(path, searchPattern, SearchOption.AllDirectories);
// Or, for better performance:
// (but breaks if you don't have access to a sub directory; see 2nd link below)
IEnumerable<string> dirNameEnumeration = Directory.EnumerateDirectories(path, searchPattern, SearchOption.AllDirectories);
How to: Enumerate Directories and Files
How to recursively list all the files in a directory in C#?
Not really an answer, but consider both of the following:
The following characters are not valid in filenames anyways so you don't have to worry about them: /\:*?"<>|.
Make sure your algorithm handles duplicate names appropriately. For example, My~Project.doc and My#Project.doc would both be renamed to My_Project.doc.
A recursive method to rename files in folders is what you want. Just pass it the root folder and it will call itself for all subfolders found.
private void SharePointSanitize(string _folder)
{
// Process files in the directory
string [] files = Directory.GetFiles(_folder);
foreach(string fileName in files)
{
File.Move(fileName, SharePointRename(fileName));
}
string[] folders = Directory.GetDirectories(_folder);
foreach(string folderName in folders)
{
SharePointSanitize(folderName);
}
}
private string SharePointRename(string _name)
{
string newName = _name;
newName = newName.Replace('~', '');
newName = newName.Replace('#', '');
newName = newName.Replace('%', '');
newName = newName.Replace('&', '');
newName = newName.Replace('*', '');
newName = newName.Replace('{', '');
newName = newName.Replace('}', '');
// .. and so on
return newName;
}
Notes:
You can replace the '' in the SharePointRename() method to whatever character you want to replace with, such as an underscore.
This does not check if two files have similar names like thing~ and thing%
class Program
{
private static Regex _pattern = new Regex("[~#%&*{}/\\|:<>?\"-]+");
static void Main(string[] args)
{
DirectoryInfo di = new DirectoryInfo("C:\\");
RecursivelyRenameFilesIn(di);
}
public static void RecursivelyRenameFilesIn(DirectoryInfo root)
{
foreach (FileInfo fi in root.GetFiles())
if (_pattern.IsMatch(fi.Name))
fi.MoveTo(string.Format("{0}\\{1}", fi.Directory.FullName, Regex.Replace(fi.Name, _pattern.ToString(), "_")));
foreach (DirectoryInfo di in root.GetDirectories())
RecursivelyRenameFilesIn(di);
}
}
Though this will not handle duplicates names as Steven pointed out.

Categories

Resources