How to get the first occurrence of char in a Substring?

I am trying to get the first occurrence at my starting point of a substring:

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

+8
source share
6 answers

To answer your real question, you can use string.IndexOf to get the first occurrence of a character. Note that you need to subtract this value from your LastIndexOf call, since Substring second parameter - the number of characters to extract, not the start and end index.

However ... Instead of parsing the names, you can simply use Path.GetFilenameWithoutExtension to get the file name directly.

+13
source

First appearance

 String.IndexOf('.') 

Last appearance

 String.LastIndexOf('.') 
+9
source

Use the IndexOf and LastIndexOf string methods to get the index of the first and last occurrence of the search string. You can use the System.IO.Path.GetExtension() , System.IO.Path.GetFileNameWithoutExtension() and System.IO.Path.GetDirectoryName() methods to analyze 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 
+6
source

file.IndexOf ("")

It should be the first appearance of ".". Otherwise, it will return -1 if not found.

+1
source

I think 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 the file name if you understand correctly:

 `ddlResources.Items.Add(new ListItem(file.Substring(0, file.LastIndexOf(".")), file ));` 

Also, you have "{}" there, as in the new ListItem {...}, which will also throw a syntax error ... Anyway, look ..

0
source

Since the original question is tagged with [regex], I will provide the following solution, however, the best answer for simple path analysis using .NET is not by regular expression.

 //extracts "filename" from "filename.resx" string name = Regex.Match("filename.resx", @"^(.*)\..+?$").Groups[1].Value; 

Instead, use an answer that relies on the Path class for simplicity. Other answers contain this information.

0
source

Source: https://habr.com/ru/post/904574/


All Articles