ReadAllLines无法正确读取带有文件路径的行

时间:2019-04-27 16:00:55

标签: c#

我正在使用“ System.IO.File.ReadAllLines”(WinForm)。一切正常,直到我到达文件中的以下行:

  <rootfile full-path="Kerp_9780553419412_epub3_opf_r1.opf" media-type="application/oebps-package+xml"/>

程序将其读取为:

  <rootfile full-path=\"content.opf\" media-type=\"application/oebps-package+xml\"/>"   string

这是代码:

string[] containerXML = System.IO.File.ReadAllLines(wrkPath + @"\META-INF\container.xml"); // read file;

int i = 0;
int IndexOfOPFLocation = containerXML[i].IndexOf("full-path");

while (i < containerXML.Count() && IndexOfOPFLocation == -1)
{
    i++;
    IndexOfOPFLocation = containerXML[i].IndexOf("full-path");
} 

string OPFLocation = containerXML[i].Substring(IndexOfOPFLocation + 10, containerXML[i].IndexOf('"', IndexOfOPFLocation + 11) - IndexOfOPFLocation);

return OPFLocation;

我尝试了多种使用@符号的方法。没有一个。

我认为问题与该行中有文件路径这一事实有关。但是我不确定。

2 个答案:

答案 0 :(得分:2)

在XML上使用字符串操作迟早会失败。
如果您想阅读epub的内容,则需要学习XmlDocument或XDocument。

让我们替换所有这些:

var doc = XDocument.Load(wrkPath + @"\META-INF\container.xml");
var ns = doc.Root.GetDefaultNamespace();
var OPFLocation = doc.Descendants(ns + "rootfile").Single().Attribute("full-path").Value;

别忘了再次使用wrkPath作为前缀。

答案 1 :(得分:1)

在代码的另一部分中确实存在一个错误,该错误将错误的文件传递给处理。

我无法删除问题。谢谢大家尤其是@Lesiak,让我再次看上去。

相关问题