I've got a list containing file information on a remote server. The files on this server have a certain file name with a suffix that increments and is always 9 characters long:
- 20220123SOMENAME000000001
- 20220132SOMENAME000000002
- 20220201SOMENAME000030000
- 20220202SOMENAME000030002
I'm trying to create a method that takes the string above as input and returns an int (1, 2, 30000 and 30002) from the examples above.
public int GetCounterFromFileName(string fileName)
{
// some logic extracting the index.
int index = 0;
return index;
}
Should I use regex to delete the prefix and infix and then get the index from the suffix?
CodePudding user response:
You can convert the last nine digits of the filename to integer by:
public int GetCounterFromFileName(string fileName)
{
return Convert.ToInt32(fileName[^9..]);
}
CodePudding user response:
I'd use substring to cut out the last nine characters, and then parse them to an int:
public int GetCounterFromFileName(string fileName)
{
return int.ParseInt(fileName.Substring(fileName.Length - 9));
}