Click here to Skip to main content
15,884,099 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,


I have a file with the name Bank_Transactions 2011-07-17_2.txt
I am trying to get 2(in bold) after datepart from the file name.
I have tried this:
file.Name.LastIndexOfAny(new char[] { '_' }) + 1
I am able to get its index but i want to get the value at that index.

Thaks in advance.
Posted

 
Share this answer
 
Comments
neha427 18-Jul-11 8:33am    
Hi,
The file name is not constant one.
The file name will be generated for each business unit in dynamic way.
Thats why I cant use substrings.Can you please suggest other alternative
C#
// first, get the name of the file without the extsension
string filename = System.IO.Path.GetFileNameWithoutExtension(@"c:\somePath\x_y 1-2-3_2.txt");
// you should now have "x_y 1-2-3_2" as the file name

// find the last underscore
int pos = filename.LastIndexOf("_");

// retrieve all of the data after the underscore
string part = "";
if (pos >= 0 && pos <= filename.Length -1)
{
    part = filename.Substring(pos);
}

// parse it into an integer
int value;
if (Int32.TryParse(part, out value))
{
    // do something with value...
}
else
{
    // error
}
 
Share this answer
 
Comments
neha427 18-Jul-11 8:35am    
Hi John,
Thank you.
This helps me.
DominicZA 18-Jul-11 8:35am    
Forgot about System.IO.Path.GetFileNameWithoutExtension :P Great answer, my 5!
Reiss 18-Jul-11 8:40am    
You may want to add some logic to check there is only one instance of the underscore character
Start here[^]. Given the position you can use substring to extract the data of interest.
 
Share this answer
 
string s = "Bank_Transactions 2011-07-17_2.txt";
s.SubString(s.LastIndexOf('_') +1);
s = s.Replace(".txt", String.Empty);


That will work...I think :P
 
Share this answer
 
Comments
neha427 18-Jul-11 8:56am    
Thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900