问题
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.
回答1:
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.
回答2:
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"
来源:https://stackoverflow.com/questions/35348836/illegal-characters-in-path-when-extracting-zip-file-with-c-sharp