How can I use IndexOf to pick a specific Character when there are more than one of them?

Posted by JimDel on Stack Overflow See other posts from Stack Overflow or by JimDel
Published on 2010-04-13T19:17:11Z Indexed on 2010/04/13 19:22 UTC
Read the original article Hit count: 235

Filed under:
|
|
|

How can I use IndexOf with SubString to pick a specific Character when there are more than one of them? Here's my issue. I want to take the path "C:\Users\Jim\AppData\Local\Temp\" and remove the "Temp\" part. Leaving just "C:\Users\Jim\AppData\Local\" I have solved my problem with the code below but this assumes that the "Temp" folder is actually called "Temp". Is there a better way? Thanks

if (Path.GetTempPath() != null) // Is it there?{
tempDir = Path.GetTempPath(); //Make a string out of it.
int iLastPos = tempDir.LastIndexOf(@"\");
if (Directory.Exists(tempDir) && iLastPos > tempDir.IndexOf(@"\"))
{
    // Take the position of the last "/" and subtract 4.
    // 4 is the lenghth of the word "temp".
    tempDir = tempDir.Substring(0, iLastPos - 4);
}}

© Stack Overflow or respective owner

Related posts about c#

Related posts about string