C# Sharpcompress error handling files containing tilde ~

60 views Asked by At

Fist up I am what I would call a copy and paste coder, learning through trial and error.

I am working on a personal project to extract a pile of compressed files (of varying compression types) to a single folder so they can then be processed. A number of these compressed files include a tilde (~) either in the file name or the name of a compressed file.

All of these files with a tilde break with an exception error... all other files are working as expected so I have narrowed it down to the tilde being the root cause and validated this my manually editing a compressed file and replacing the ~ with _ and everything works.

Here is the error that is collected by the exception:

2023-11-19 13:07:30,023 [ERROR] - Extract Source Compressed Files: Entry is trying to write a file outside of the destination directory.

Here is my code, which is pretty much copy and paste from the example given by SharpCompress:

public static void extractcompressedfiles_mk2(string Compressedfilepath, string extractPath)
{
    // If directory already exist, CreateDirectory does nothing
    System.IO.Directory.CreateDirectory(extractPath);
    try
    {
        // Extract current zip file
        using (Stream stream = File.OpenRead(Compressedfilepath))
        using (var reader = ReaderFactory.Open(stream))
        {
            while (reader.MoveToNextEntry())
            {
                if (!reader.Entry.IsDirectory)
                {
                    Console.WriteLine(reader.Entry.Key);
                    reader.WriteEntryToDirectory(extractPath, new ExtractionOptions()
                    {
                        ExtractFullPath = true,
                        Overwrite = true
                    });
                }
            }
        }
    }
    catch (Exception e)
    {
        Common.Globals.intExceptionErrors++;
        Logging.system.Error($"Extract Source Compressed Files: {e.Message}");
    }

I did find the following question that might provide more insight - Unable to add files with name containing tilde, '~' followed by a number

Does anyone have any ideas as to how I can resolve or circumvent this error, my plan B is to use 7zip and run the commands via Windows but this feels naughty!

Cheers Euge

0

There are 0 answers