Search for file with only part of its name in C#

Asked

Viewed 2,520 times

2

I need to find a file automatically without opening 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 this final part will never repeat. I even made this code here below but I was not successful, because I can get all the files from this directory but I am not able to identify the file that ends 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;
    }

3 answers

4

Instead of

foreach (FileInfo f in diretorio.GetFiles())

utilize

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

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

2

As a curiosity, you can also use EnumerateFiles(...). Unlike GetFiles(...) who makes the search in its entirety and only then returns a string[], EnumerateFiles(...) returns a IEnumerable that can be iterated in a lazy way.

Thus the use would be:

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

Note, if you want to search the subdirectories, use the Overload EnumerateFiles(string, SearchOption):

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

1


You can do using Linq

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

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

var arquivo = diretorio.GetFiles().Single(x => x.Name.EndsWith(ParteFinal));

Browser other questions tagged

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