Click here to Skip to main content
15,890,512 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have a c# program which will unzip all the zipped file.But I need to open the unzipped folder and visible only .txt files.How can I do that?

below code will unzip all files but i want to open that folder and get only selected files(.txt or .xlsx)

in my destination path(here extractPathForCurrentZip) i shoud only see .txt files from diffrent unzipped folder

my code to unzip:

What I have tried:

C#
string startPath = @"C:\zipdirectory\";
       string extractPath = @"C:\unzipdirectory\";
       Directory.GetFiles(startPath, "*.zip", SearchOptions.AllDirectories).ToList()
           .ForEach(zipFilePath => {
               var extractPathForCurrentZip = Path.Combine(extractPath, Path.GetFileNameWithoutExtension(zipFilePath));
               if(!Directory.Exists(extractPathForCurrentZip))
               {
                   Directory.CreateDirectory(extractPathForCurrentZip);
               }
               ZipFile.ExtractToDirectory(zipFilePath, extractPathForCurrentZip);
       });
Posted
Updated 13-Apr-22 16:03pm
v2

1 solution

Create a ZipArchive from the ZipFile, and use the ExtractToFile method if the file type is acceptable:
C#
using (ZipArchive zip = ZipFile.Open(zipfile, ZipArchiveMode.Read))
    foreach (ZipArchiveEntry entry in zip.Entries)
        {
        string ext = Path.GetExtension(entry.Name).ToLower();
        if(ext == ".txt" || ext == ".xlsx")
            {
            ... sort out where you want to put it ...
            entry.ExtractToFile(outputFileNameAndPath);
            }
        }
 
Share this answer
 
Comments
Maciej Los 14-Apr-22 14:26pm    
5ed!
[no name] 18-Apr-22 1:54am    
ZipFile.Open(zipfile, ZipArchiveMode.Read)).here "zipfile" means what
OriginalGriff 18-Apr-22 2:40am    
well, what you you think it might mean?
What *might* be useful when opening a file?
[no name] 18-Apr-22 4:07am    
i am getting error on that.i have given the path
OriginalGriff 18-Apr-22 4:43am    
ANd what error might that be?
What is the exact path you have given as shown with the debugger? How doesthat compare to the file system?

Remember that we can't see your screen, access your HDD, or read your mind - we only get exactly what you type to work with - we get no other context for your project.
Imagine this: you go for a drive in the country, but you have a problem with the car. You call the garage, say "it broke" and turn off your phone. How long will you be waiting before the garage arrives with the right bits and tools to fix the car given they don't know what make or model it is, who you are, what happened when it all went wrong, or even where you are?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900