3

I'm trying to write a method that extracts a zip file to a directory, finds a file in the extracted contents, reads the text in that file to a string, and returns that string. Here is my attempt

private string _getDataFile(string zipFile)
{

    string pathToFolder = @"C:\Path\To\The\File";

    foreach (char c in Path.GetInvalidPathChars())
    {
        pathToFolder = Regex.Replace(pathToFolder, c.ToString(), "");
    }
    string pathToFile = pathToFolder + @"\model.dat";
    ZipFile.ExtractToDirectory(zipFile, pathToFolder);
    string dataToReturn = File.ReadAllText(pathToFile);
    return dataToReturn;
}

However, despite my foreach loop replacing illegal path characters, the program still throws an illegal characters in path exception at the ZipFile.ExtractToDirectory line no matter what directory I try to use and I have no idea why. Any help would be greatly appreciated.

Nick Gilbert
  • 4,159
  • 8
  • 43
  • 90

2 Answers2

2

According to a similar post, it looks like you may have a problem with a file name inside the target zip file; it is not a problem with your specified zip file name or directory. Try extracting the contents of the file manually to see if there are unusual file names.

Community
  • 1
  • 1
T. Yates
  • 192
  • 11
  • I'll accept this answer because you're kind of right. I was passing in the zip file with Encoding.UTF8.GetString(ComponentFiles.test). Turns out that did not do what I thought it did. – Nick Gilbert Feb 11 '16 at 20:12
1

You can iterate through all the entries and sanitize the filenames before extracting them by using this snippet that I wrote here: ZipFile.ExtractToDirectory "Illegal characters in path"

Community
  • 1
  • 1
nramirez
  • 5,230
  • 2
  • 23
  • 39