解析 XML 文件时的编码问题
每个人。我正在 Mono 2.4、Ubuntu 10.10 中开发一个小型 ASP.NET Mvc 项目。有一个对象数组,每个对象都对应一个特定的xml文件。 xml 的读取是使用 XmlTextReader 执行的。这不起作用,因为 xml 文件具有罕见的“cp866nav”编码,XmlTextReader 不支持这种编码(“System.ArgumentException:不支持编码名称'cp866nav'”)。但如果将 xml 标头中的编码更改为“cp866”,它就可以正常工作。我找到了一种解决方案,其中包括使用具有某种编码而不是文件名的 StreamReader 初始化 XmlTextReader,如下面的代码所示:
XmlTextReader reader = new XmlTextReader(new StreamReader(Server.MapPath(filename), Encoding.GetEncoding("cp866")));
问题是包含 xml 文件的目录是只读的(我无法更改它),所以我得到 “System.UnauthorizedAccessException:对路径 '' 的访问被拒绝。
”。相当奇怪,因为用文件名初始化的 XmlTextReader 似乎读取了文件。
考虑到程序无法修改或创建文件,有什么解决方案吗?
everyone. I'm developing a small ASP.NET Mvc project in Mono 2.4, Ubuntu 10.10. There is an array of objects, each one of them corresponds to a certain xml file. Reading of the xmls is performed with XmlTextReader. That does not work because xml files have rare "cp866nav" encoding, which is not supported by XmlTextReader ("System.ArgumentException: Encoding name 'cp866nav' not supported
"). But it works fine if encoding in xml header is changed to "cp866". I found a kind of solution which consists in initializing XmlTextReader with a StreamReader with a certain encoding instead of file name, like in the code below:
XmlTextReader reader = new XmlTextReader(new StreamReader(Server.MapPath(filename), Encoding.GetEncoding("cp866")));
The issue is that the directory which contains xml files is read only (I can not change it), so I get
"System.UnauthorizedAccessException: Access to the path '' is denied.
". Rather strange, because XmlTextReader initialized with a filename seems to read the files.
Is there any solution, considering that program cannot modify or create files?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您的问题是文件访问而不是编码,我建议尝试使用正确的标志 FileStream(name, FileMode.Open, FileAccess.Read) 自行打开文件作为流,然后调用另一个采用 Stream 的构造函数 StreamReader 。
(完成后不要忘记处理流/读取器)。
As your problem is with file access rather than encoding I'd recommend trying to open file as stream yourslef with correct flags FileStream(name, FileMode.Open, FileAccess.Read) and then calling the other constructor StreamReader that takes Stream.
(Don't forget to dispose stream/readers when you are done).