Find file having only part of its name in C #

2

I need to find a file automatically without having to open a check box for the user to select the file. Where I already have the directory of the folder where this file will stay and I also know the part of the final name of this file, and that final part will never repeat itself. I got to do this code here but I did not succeed, because I can get all the files in this directory but I can not identify the file ending with the given name:

private string localizarArquivo()
    {
        DirectoryInfo diretorio = new DirectoryInfo(NFe.DiretorioLog); // C:\Users\WIN\Documents\Visual Studio 2015\Projects\Demo NFe - VS2012 - C#\bin\Debug\Log\
        string chave = edtIdNFe.Text.Trim();
        string ParteFinal = chave + "-env-sinc-ret.xml"; // 26151003703802000156550100000004521376169520-env-sinc-ret.xml

        string ArquivoLog = String.Empty; // Deverá ser: diretorio + ??????? +  ParteFinal

        foreach (FileInfo f in diretorio.GetFiles())
        {
            if (f.Extension.ToLower() == ParteFinal)
                ArquivoLog = f.ToString();
        }

        if (File.Exists(ArquivoLog))
            return ArquivoLog;

        return null;
    }
    
asked by anonymous 28.10.2015 / 15:53

3 answers

1

You can do this using Linq

var arquivos = diretorio.GetFiles().Where(x => x.Name.EndsWith(ParteFinal));

If you are sure that there is only one file, you can use Single()

var arquivo = diretorio.GetFiles().Single(x => x.Name.EndsWith(ParteFinal));
    
28.10.2015 / 16:02
4

Instead of

foreach (FileInfo f in diretorio.GetFiles())

use

foreach (FileInfo f in diretorio .GetFiles("*" + ParteFinal))

So the source of your forEach will already be filtered, content only the files whose names match the mask.

    
28.10.2015 / 16:01
2

For the sake of curiosity, you can also use EnumerateFiles(...) . Unlike GetFiles(...) that does the search in totality and only then returns a string[] , EnumerateFiles(...) returns a IEnumerable that can be iterated lazily.

So, the use would be:

foreach(var f in directorio.EnumerateFiles(string.Format("*{0}*", ParteFinal))
{}

Note, if you want to look in subdirectories, use the overload EnumerateFiles(string, SearchOption) :

foreach(var f in directorio.EnumerateFiles(string.Format("*{0}*", ParteFinal), SearchOptions.AllDirectories)
{}
    
28.10.2015 / 16:07