Retrieve part of a string (split or index)

Asked

Viewed 254 times

1

I have a folder structure like this:

bco_img/3/foto_produto/
bco_img/3/foto_produto/tb/
bco_img/4/foto_produto/
bco_img/4/foto_produto/tb/
etc...

I want to recover the folder /3/ after /4/ and also the name of the photos that are inside each folder, e.g.: folder: /3/ photo: Xyz.jpg I did something like this:

string url_Fonte = Server.MapPath("BCO_IMG");

DirectoryInfo diretorio = new DirectoryInfo(url_Fonte);
   FileInfo[] Arquivos = diretorio.GetFiles("*.jpg", SearchOption.AllDirectories);
      foreach (FileInfo fileinfo in Arquivos)
      {
       string nome_dir =  fileinfo.DirectoryName;
       string v1 = nome_dir.IndexOf(@"BCO_IMG\").ToString();
    // aqui qual é o melhor? fazer uma função para recuperar pelo indexOF ou criar um Array com Split() ?

      string nome_foto = fileinfo.Name;
      }
  • 3

    Is this what you want? http://answall.com/questions/35400/como-obten-um-trecho-de-umastring/35401#35401

2 answers

0

By the way, the format "url_Fonte/sua pasta/etc./nomearquivo" is fixed. Then..

string subdir = nome_dir.ToLower().Replace(url_Fonte.ToLower() + "/", "").Split('/')[0];
// ou 
string subdir = nome_dir.Split('/')[1];

Then you can involve the subdir bars ("/" + subdir + "/").

To get the file name:

string nomearquivo = nome_dir.Split('/').ToList().Last();
// ou
string sub = nome_dir.Split('/');
string nomearquivo = sub.IndeOf(sub.Length - 1);
  • did not work, but the link of bigwon, led to a url that gives a solution similar to yours that ended up working. Thank you

0


I got through the link maniero

 string nome_dir =  fileinfo.DirectoryName;
string[] Valores = nome_dir.ToString().Split(new char[] { '\\' });
var palavra = Valores[7];

I think with regular expression it would also

Regex regex = new Regex("^~/BCO_IMG/(?<output>[Z0-9]+)/*/.*$");
GroupCollection capturas = regex.Match(source).Groups;
Response.Write(capturas["output"]);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.