简体   繁体   中英

Get the last part of file name in C#

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM