Home > Software design >  Split a string (file name) using index position
Split a string (file name) using index position

Time:07-28

I need to separate the file name into an array of two strings.

The file name looks like this: IMG-20190604-WA0005.jpg

An array that I want:

[0] = "IMG-20190604-WA0005"

[1] = "jpg"

I got index position using LasIndexOf('.')

CodePudding user response:

Don't use string methods but the available methods in System.IO.Path:

string file = "IMG-20190604-WA0005.jpg";
string filenameWithoutExtension = Path.GetFileNameWithoutExtension(file);
string extension = Path.GetExtension(file); 

If you don't want the . at the beginning, remove it:

string extension = Path.GetExtension(file).TrimStart('.'); 
  • Related