使用C#提取zip文件时路径中的非法字符 [英] Illegal Characters in Path when extracting zip file with C#
问题描述
我正在尝试编写一种方法,将zip文件提取到目录中,在提取的内容中找到文件,将文件中的文本读取为字符串,然后返回该字符串.这是我的尝试
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;
}
但是,尽管我的foreach循环替换了非法的路径字符,但无论我尝试使用哪个目录,我都不知道为什么,该程序仍会在ZipFile.ExtractToDirectory行的路径异常中抛出非法字符.任何帮助将不胜感激.
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.
推荐答案
根据类似的帖子,看来您在目标zip文件中的文件名可能有问题;您指定的zip文件名或目录不是问题.尝试手动提取文件内容,以查看是否存在异常的文件名.
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.
这篇关于使用C#提取zip文件时路径中的非法字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!