Reputation: 5859
I'm trying to get the first occurrence in my substring start point:
string dir = Request.MapPath(Request.ApplicationPath) + "\\App_GlobalResources\\";
foreach (var file in Directory.EnumerateFiles(dir, "*.resx"))
{
ddlResources.Items.Add(new ListItem { Text = file.Substring(firstoccuranceof("."), file.LastIndexOf(".")), Value = file });
}
if I do file.Substring(file.IndexOf("."), file.LastIndexOf(".")) I get an error
Upvotes: 20
Views: 73432
Reputation: 289
Here you go!)
Using a string variable type
int index = str.IndexOf(@"\");
"C:\Users\somebody\Desktop\aFolder\someFile"
Upvotes: 0
Reputation: 28869
Because the original question is marked with the [regex] tag, I'll provide the following solution, however the best answer for simple parsing of paths using .NET is not by regex.
//extracts "filename" from "filename.resx"
string name = Regex.Match("filename.resx", @"^(.*)\..+?$").Groups[1].Value;
Use an answer that relies on the Path
class instead, for simplicity. Other answers contain that info.
Upvotes: 0
Reputation: 22372
I think that in your particular case you are NOT trying to get IndexOf... Instead you need to use 0 because you are trying to create a key based on filename if understand correctly:
`ddlResources.Items.Add(new ListItem(file.Substring(0, file.LastIndexOf(".")), file ));`
Also, you have '{}' in there as in new ListItem { ... } which is also going to cause a syntax error... Anyhow have a look..
Upvotes: 1
Reputation: 94645
Use IndexOf
and LastIndexOf
string methods to get index of first and last occurrence of "search" string. You may use System.IO.Path.GetExtension()
, System.IO.Path.GetFileNameWithoutExtension()
, and System.IO.Path.GetDirectoryName()
methods to parse the path.
For instance,
string file = @"c:\csnet\info.sample.txt";
Console.WriteLine(System.IO.Path.GetDirectoryName(file)); //c:\csnet
Console.WriteLine(System.IO.Path.GetFileName(file)); //info.sample.txt
Console.WriteLine(System.IO.Path.GetFileNameWithoutExtension(file));//info.sample
Console.WriteLine(System.IO.Path.GetExtension(file)); //.txt
Upvotes: 8
Reputation: 591
file.IndexOf(".")
Should get you the first occurence of ".". Otherwise it will return -1 if not found.
Upvotes: 1
Reputation: 564433
To answer your actual question - you can use string.IndexOf
to get the first occurrence of a character. Note that you'll need to subtract this value from your LastIndexOf
call, since Substring
's second parameter is the number of characters to fetch, not a start and end index.
However... Instead of parsing the names, you can just use Path.GetFilenameWithoutExtension to get the filename directly.
Upvotes: 23
Reputation: 12346
First occurence
String.IndexOf('.')
Last occurence
String.LastIndexOf('.')
Upvotes: 19