How to select specific files in a folder?

Asked

Viewed 64 times

1

I’m making a Console Application in C# which, given an array of file names it returns the address of each and adds them to a Dotnetzip Zipfile.

Currently I code lies like this:

string[] nomes = { 
  "C:\\users\\fabio\\desktop\\pastateste\\teste1.txt",
  "C:\\users\\fabio\\desktop\\pastateste\\teste5.txt",
  "C:\\users\\fabio\\desktop\\pastateste\\teste6.txt",
  "C:\\users\\fabio\\desktop\\pastateste\\teste10.txt"};

            using(ZipFile zip = new ZipFile())
            {
                foreach (string item in nomes)
                {
                    if (File.Exists(item))
                        zip.AddFile(item, "arquivos"); 
                }
                zip.Save("C:\\users\\fabio\\desktop\\compactteste.zip");

The "pastateste" folder contains . txt files from 1 to 10 and I just select {1,5,6,10}, but passing the full address of each file in the names array.

How can I rummage through the "pastateste" folder, pick up the address of the test files{1,5,6,10} and store them in another array?

  • System.IO.Path.GetFullPath may be what you seek

  • I believe that using the methods of the System.IO library you can, look at the File and Directory classes. To list files from a directory you can use Directory.Getfiles()

  • Fabio, I can not understand what you want to do effectively... You can [Dit] your question and try to be a little more specific?

  • @LINQ Edited! I tried to be clearer now.

1 answer

0


It’s quite simple. You can simply get all the files from "pastateste" and apply to the returned collection a filter using the Where linq.

In the example below is done the file filter using a regex that tries to find by the following pattern:

  • the file name must contain the word "test";
  • then you need to find number 1, 5, 6 or 10;
  • then need to find the word ".txt"; and
  • string needs to finish after this
const string caminhoBase = @"C:\Users\fabio\Desktop\pastateste";
var regexArquivo = new Regex("teste(1|5|6|10).txt$");
    
var arquivos = Directory.GetFiles(caminhoBase).Where(a => regexArquivo.IsMatch(a)); 
  • It worked correctly, thank you. If the file name was "arquivoteste1compress.txt", regex would only be able to find it with "test(1). txt$" ?

  • @Fabiohagiwara In this case you need to adapt the regular expression a little to accept any string at the beginning and between teste1 and .txt. It would be something like: (\S)*teste1(\S)*\.txt$. But you need more details to answer by matching all the cases, because this pattern would recognize the string teste1.txt, for example.

Browser other questions tagged

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