Finding files starting with variable given by users - c#

System.IO.FileInfo[] fileNames = dir.GetFiles("*check*.*");
This returns me any files with name check. But what i want is return those file starting with string given by users.
Example
string word = Console.Readkey();
System.IO.FileInfo[] fileNames = dir.GetFiles("*word*.*");
I tried this
System.IO.FileInfo[] fileNames = dir.GetFiles("*"+word+"*".*");
But this didnt work

First of all, Console.ReadKey() reads a key which I think you don't intend it to do, so change it to Console.ReadLine().
That being said, if you want to use the variable word, you don't put within the string. Put it outside and either concatenate with the rest of the pattern or use String.Format().
So use this code:
string word = Console.ReadLine();
System.IO.FileInfo[] fileNames = dir.GetFiles(String.Format("{0}*.*", word));

System.IO.FileInfo[] fileNames = dir.GetFiles(string.Format("{0}*.*", word));

You need to use this
public static string[] GetFiles(
string path,
string searchPattern
)
method from Directory class. The version with one string parameter accepts the path.

Related

Taking the last Substring of a string in C#

I have a string
"\uploads\test1\test2.file"
What's the method to get just "test2.file"?
What I have in my mind is to get the last index of "\" and then perform a string.substring(last index of "\") command on it?
Is there a method that takes just the word after the last "\"?
Use the method Path.GetFileName(path); in System.IO namespace, it is much more elegant than doing string operations.
You could use LINQ:
var path = #"\uploads\test1\test2.file";
var file = path.Split('\\').Last();
You might want to validate the input, if you're concerned about path potentially being null or whatnot.
You could do something like this:
string path = "c:\\inetpub\\wwwrroot\\images\\pdf\\admission.pdf";
string folder = path.Substring(0,path.LastIndexOf(("\\")));
// this should be "c:\inetpub\wwwrroot\images\pdf"
var fileName = path.Substring(path.LastIndexOf(("\\"))+1);
// this should be admin.pdf
For more take a look at here How do I get the last part of this filepath?
Hope it helps!
You can use the Split method:
string myString = "\uploads\test1\test2.file";
string[] words = myString.Split("\");
//And take the last element:
var file = words[words.lenght-1];
using linq:
"\uploads\test1\test2.file".Split('\\').Last();
or you can do it without linq:
string[] parts = "\uploads\test1\test2.file".Split('\\');
last_part=parts[parts.length-1]

How can I replace the same name of a file using regex but in another format?

I am new in programming and not so good about regex. I wish to load / read a csv File and then save in a txt File using the same name of csv File. I will give an example.
D:\Project\File\xxx.csv
After I load this file, I want to get the name "xxx" and save it in a txt file:
D:\Project\File\xxx.txt
Or maybe in another folder, for example:
D:\Project\Specifications\PersonInfo.csv
save to
D:\Project\DataBank\PersonInfo.txt
This can be accomplished in many ways.
Maybe what you're lacking is knowledge of the System.IO.Path class (MSDN article here).
For instance changing the extension could be accomplished like so:
string originalFilePath = #"D:\Project\File\xxx.csv";
string newFilePath = Path.ChangeExtension(originalFilePath, ".txt");
Note: You need to explicitate the leading dot (".") for the extension.
Here's some "Path algebra" fun you could combine to create your desired effects:
string originalFilePath = #"D:\Project\File\xxx.csv";
string thePath = Path.GetDirectoryName(originalFilePath);
// will be #"D:\Project\File"
string filename = Path.GetFileName(originalFilePath);
// will be "xxx.csv"
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(originalFilePath);
// will be "xxx"
string recombinedFilePath = Path.Combine( #"D:\OtherFolder", "somethingElse.txt" );
// will be #"D:\OtherFolder\somethingElse.txt"
Note: Path.Combine knows how to handle extra/missing leading/trailing backslashes.
For example:
Path.Combine(#"D:\MyFolder1", #"MyFolder2\MyFile.txt")
Path.Combine(#"D:\MyFolder1\", #"MyFolder2\MyFile.txt")
Path.Combine(#"D:\MyFolder1", #"\MyFolder2\MyFile.txt")
Path.Combine(#"D:\MyFolder1\", #"\MyFolder2\MyFile.txt")
will all yield the same result: #"D:\MyFolder1\MyFolder2\MyFile.txt"
You do not need regex for that, because .NET provides a System.IO.Path class for dealing specifically with file name manipulations.
For example, to replace .csv with .txt you can use this call:
var csvPath = #"D:\Project\File\xxx.csv";
var txtPath = Path.Combine(
Path.GetDirectoryName(csvPath)
, Path.GetFileNameWithoutExtension(csvPath)+".txt"
);
You use a similar trick to replace other parts of the file path. Here is how you change the name of the top directory:
var csvPath = #"D:\Project\Specifications\xxx.csv";
var txtPath = Path.Combine(
Path.GetDirectoryName(Path.GetDirectoryName(csvPath))
, "DataBank"
, Path.GetFileNameWithoutExtension(csvPath)+".txt"
);
You don't need Regex.
You can use Path.GetFileName or Path.GetFileNameWithoutExtension:
string fileName = Path.GetFileNameWithoutExtension("D:\Project\Specifications\PersonInfo.csv");
If you want to use regex for this, this regex will get the part you want:
([^\\]+)\.[^.\\]+$
The first group (in the parentheses) matches one or more characters (as many as possible) which is not a backslash. Then there need to be a literal dot. Then one or more characters (as many as possible) that are not a dot or backslash, then the end of the string. The group captures the wanted part.

to get the file names in a directory (without getting path) in c#

i want to store the name of all file present in c:\test\ in a string array s[]
let there are files name a1.txt , a2.txt , a3.txt ... in c:\test
i want to store in s[0]= a1.txt s[1]= a2.txt and like that
i have used the code
s = Directory.GetFiles(#"c:\\test");
but it makes s[0]= c:\test\a1.txt
i dont want c:\test , i only want a1.txt
so is there any method to store only the file name but not the path of the file
i would also like to know if there is any method to remove some characters from each string of a string array
like cutting 5 characters from the beginning of each string of a string array this may also solve my problem.
Use GetFileName to extract file name from path. Like below
string[] s = Directory.GetFiles(#"c:\\test");
foreach (string filename in s)
{
string fname = Path.GetFileName(filename);
}
maybee duplicate from hare..
any way #Vasea gives us :
Directory.GetFiles(#"c:\test", "*", SearchOption.TopDirectoryOnly).Select(f => Path.GetFileName(f));

File names matching "..\ThirdParty\dlls\*.dll"

Is there an easy way to get a list of filenames that matach a filename pattern including references to parent directory? What I want is for "..\ThirdParty\dlls\*.dll" to return a collection like ["..\ThirdParty\dlls\one.dll", "..\ThirdParty\dlls\two.dll", ...]
I can find several questions relating matching files names including full path, wildcards, but nothing that includes "..\" in the pattern. Directory.GetFiles explicitly disallows it.
What I want to do with the names is to include them in a zip archive, so if there is a zip library that can understand relative paths like this I am happier to use that.
The pattern(s) are coming from an input file, they are not known at compile time. They can get quite complex, e.g ..\src\..\ThirdParty\win32\*.dll so parsing is probably not feasible.
Having to put it in zip is also the reason I am not very keen on converting the pattern to fullpath, I do want the relative paths in zip.
EDIT: What I am looking for really is a C# equivalent of /bin/ls.
static string[] FindFiles(string path)
{
string directory = Path.GetDirectoryName(path); // seperate directory i.e. ..\ThirdParty\dlls
string filePattern = Path.GetFileName(path); // seperate file pattern i.e. *.dll
// if path only contains pattern then use current directory
if (String.IsNullOrEmpty(directory))
directory = Directory.GetCurrentDirectory();
//uncomment the following line if you need absolute paths
//directory = Path.GetFullPath(directory);
if (!Directory.Exists(directory))
return new string[0];
var files = Directory.GetFiles(directory, filePattern);
return files;
}
There is the Path.GetFullPath() function that will convert from relative to absolute. You could use it on the path part.
string pattern = #"..\src\..\ThirdParty\win32\*.dll";
string relativeDir = Path.GetDirectoryName(pattern);
string absoluteDir = Path.GetFullPath(relativeDir);
string filePattern = Path.GetFileName(pattern);
foreach (string file in Directory.GetFiles(absoluteDir, filePattern))
{
}
If I understand you correctly you could use Directory.EnumerateFiles in combination with a regular expression like this (I haven't tested it though):
var matcher = new Regex(#"^\.\.\\ThirdParty\\dlls\\[^\\]+.dll$");
foreach (var file in Directory.EnumerateFiles("..", "*.dll", SearchOption.AllDirectories)
{
if (matcher.IsMatch(file))
yield return file;
}

Parse directory name from a full filepath in C#

If I have a string variable that has:
"C:\temp\temp2\foo\bar.txt"
and I want to get
"foo"
what is the best way to do this?
Use:
new FileInfo(#"C:\temp\temp2\foo\bar.txt").Directory.Name
Far be it for me to disagree with the Skeet, but I've always used
Path.GetFileNameWithoutExtension(#"C:\temp\temp2\foo\bar.txt")
I suspect that FileInfo actually touches the file system to get it's info, where as I'd expect that GetFileNameWithoutExtension is only string operations - so performance of one over the other might be better.
I think most simple solution is
DirectoryInfo dinfo = new DirectoryInfo(path);
string folderName= dinfo.Parent.Name;
Building on Handleman's suggestion, you can do:
Path.GetFileName(Path.GetDirectoryName(path))
This doesn't touch the filesystem (unlike FileInfo), and will do what's required. This will work with folders because, as the MSDN says:
Return value: The characters after the last directory character in path. If the last
character of path is a directory or volume separator character, this
method returns String.Empty. If path is null, this method returns
null.
Also, looking at the reference source confirms that GetFilename doesn't care if the path passed in is a file or a folder: it's just doing pure string manipulation.
I had an occasion when I was looping through parent child directories
string[] years = Directory.GetDirectories(ROOT);
foreach (var year in years)
{
DirectoryInfo info = new DirectoryInfo(year);
Console.WriteLine(info.Name);
Console.WriteLine(year);
//Month directories
string[] months = Directory.GetDirectories(year);
foreach (var month in months)
{
Console.WriteLine(month);
//Day directories
string[] days = Directory.GetDirectories(month);
foreach (var day in days)
{
//checkes the files in the days
Console.WriteLine(day);
string[] files = Directory.GetFiles(day);
foreach (var file in files)
{
Console.WriteLine(file);
}
}
}
}
using this line I was able to get only the current directory name
DirectoryInfo info = new DirectoryInfo(year);
Console.WriteLine(info.Name);
It'll depend on how you want to handle the data, but another option is to use String.Split.
string myStr = #"C:\foo\bar.txt";
string[] paths = myStr.Split('\\');
string dir = paths[paths.Length - 2]; //returns "foo"
This doesn't check for an array out of bounds exception, but you get the idea.

Categories

Resources