Illegal Characters in Path when extracting zip file with C#

一个人想着一个人 提交于 2020-05-15 08:54:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!