Hi I would like to know how to validate a filename in C# to check that it ends with a certain word (not just contains but is located at the end of the filename)
e.g I want to modify certain files that end with the suffix Supplier so I want to validate each file to test if it ends with Supplier, so LondonSupplier.txt, ManchesterSupplier.txt and BirminghamSupplier.txt would all be validated and return true but ManchesterSuppliers.txt wouldn't.
is this even possible? I know you can validate a filename to test for a certain word anywhere within a filename but is it possible to do what i'm suggesting?
Try:
Path.GetFileNameWithoutExtension(path).EndsWith("Supplier")
if (myFileName.EndsWith("whatever"))
{
// Do stuff
}
By utilizing the System.IO.Path.GetFileNameWithoutExtension(string) method, you can extract the filename (sans extension) from a string. For example, calling it with the string C:\svn\trunk\MySourceFile.cs would return the string MySourceFile. After this, you can use the String.EndsWith method to see if your filename matches your criteria.
Linq solution:
var result = FilePaths.Where(name => Path.GetFileNameWithoutExtension(name).EndsWith("Supplier"))
.Select(name => name).ToList();
Assuming that FilePaths is a list containing all the paths.
Related
This is the simple C# code I wrote :
string file = #"D:\test(2021/02/10).docx";
var fileName = Path.GetFileNameWithoutExtension(file);
Console.WriteLine(fileName);
I thought I would get the string "test(2021/02/10)" , but I got this result "10)".
How can I solve such a problem?
I just wonder why would you want such behavior. On windows slashes are treated as separator between directory and subdirectory (or file).
So, basically you are not able to create such file name.
And since slashes are treated as described, it is very natural that method implementation just checks what's after last slash and extracts just filename.
If you are interested on how the method is implemented take a look at source code
Ok what I am doing is selecting a file name and saving the filename only. What I need to do is remove certain text from it but it changes and that's the issue I am having.
The main one is it has name_zm and I want to remove _zm from the name.
But some other files have ak47_fmg_mp and all i want is the first before the _
but not sure how to accomplish this.
I have tried text replace regex even but none of it has worked
string result = nyu_res.filename;
result = result.Replace("_zm", "");
Well when i select a file it saves the filename in this example. Lets say I selected
m14_zm
What I want to do is get m14 and thats it. Same with the others. Just want to get to the first '_'. I tried the code above but could not get it to work.
Any help would be much appreciated.
Use Split('_') and take the first one.
Then you don't have to check if it contains _ or not.
result = result.Split('_')[0];
Check your string for Null/Empty and '_' then you can use Substring and IndexOf to do that :
var result = "fileName_zm";
if(!string.IsNullOrEmpty(result) && result.Contains('_'))
{
result = result.Substring(0, result.IndexOf("_"));
}
Advantage: if string is Null/Empty it will short circuit and you will save few cycles of CPU.
I need get last part means the numeric value(318, 319) of the following text (will vary)
C:\Uploads\X\X-1\37\Misc_318.pdf
C:\Uploads\X\X-1\37\Misc_ 319.pdf
C:\Uploads\X\C-1\37\Misc _ 320.pdf
Once I get that value I need to search for the entire folder. Once I find the files name with matching number, I need to remove all spaces and rename the file in that particular folder
Here is What I want
First get the last part of the file(numeric number may vary)
Based upon the number I get search in the folder to get all files names
Once I get the all files name check for spaces with file name and remove the spaces.
Finding the Number
If the naming follows the convention SOMEPATH\SomeText_[Optional spaces]999.pdf, try
var file = System.IO.Path.GetFileNameWithoutExtension(thePath);
string[] parts = file.split('_');
int number = int.Parse(parts[1]);
Of course, add error checking as appropriate. You may want to check that there are 2 parts after the split, and perhaps use int.TryParse() instead, depending on your confidence that the file names will follow that pattern and your ability to recover if TryParse() returns false.
Constructing the New File Name
I don't fully understand what you want to do once you have the number. However, have a look at Path.Combine() to build a new path if that's what you need, and you can use Directory.GetFiles() to search for a specific file name, or for files matching a pattern, in the desired directory.
Removing Spaces
If you have a file name with spaces in it, and you want all spaces removed, you can do
string newFilename = oldFilename.Replace(" ", "");
Here's a solution using a regex:
var s = #"C:\Uploads\X\X-1\37\Misc_ 319.pdf";
var match = Regex.Match(s, #"^.*?(\d+)(\.\w+)?$");
int i = int.Parse(match.Groups[1].Value);
// do something with i
It should work with or without an extension of any length (as long as it's a single extension, not like my file 123.tar.gz).
In the following C# method, I know that the Directory.GetFileNsmes() does return the list of files. And, I can add in the Where contains(contact) which works. However for the life of me I can not determine why the searchPatter.IsMatch() fails to find files. I've tested the pattern in http://regexpal.com/ and it qorks as expected. The namePattern is "^\d{3}(.*).pdf" and there should be a match.
public static List<string> GetFileNames(string pathName, string namePattern, string contact)
{
var searchPattern = new Regex(namePattern, RegexOptions.IgnoreCase);
var files = Directory.GetFiles(pathName).Where(f => searchPattern.IsMatch(f));
//.Where(f => f.Contains(contact));
return files.ToList();
}
If this is already answered somewhere please let me know but I've not been able to locate it. I thought this it was pretty simple and straight forward.
Directory.GetFiles will return fill file path which will be Drive\Directory\File.ext. That's why your pattern doesn't seem to match. You need FileName alone as subject. Try this
var files = Directory.GetFiles(pathName)
.Where(f => searchPattern.IsMatch(Path.GetFileName(f)));
Directory.GetFiles() returns a list of filenames appended to the path supplied as a parameter. Your regular expression is "^\d{3}(.*).pdf", that is a string beginning with three digits. If you supplied a string that's an absolute path, it will start with either "/" on Unix or "C:\" on Windows and if it's a relative path, it will start with a directory name. Your code would work if pathName was just an empty string and you were searching the current directory.
i have a project to make and i want in option 2 the user to give an extension/keyword for example and the program to search the directory for this and print all the files that include this extension/keyword and i need some help if it's possible.
Then use another overload of the Directory.GetFiles() method which accepts a search pattern as a parameter.
Check it out on MSDN. And here is an example.
var files = Directory.GetFiles(#"c:\", "*.exe");
Obviously, replace that second argument with a variable name where you store an input from a user.
Or perhaps something like:
IEnumerable<string> results = filePaths.Where(x => x.EndsWith(".exe"));