在我的ASP.NET应用程序中,一个应该将文件写入磁盘的方法有时会意外地以文件名写入文件NOT_A_VALID_FILESYSTEM_PATH
.
(简化)代码是:
private void WriteFile(string fileID) { string fileName = Server.MapPath("/Data/" + fileID + ".xml"); // (More code that writes data to that file...) }
为什么Server.MapPath返回字符串"NOT_A_VALID_FILESYSTEM_PATH"?
当满足以下两个条件时,Server.MapPath返回字符串"NOT_A_VALID_FILESYSTEM_PATH":
提供给Server.MapPath的参数包含一个不能出现在有效文件名中的字符,例如冒号(":")或问号("?");
在应用程序的web.config文件中,system.web/httpRuntime元素包含属性relaxedUrlToFileSystemMapping ="true".
如果web.config没有relaxedUrlToFileSystemMapping="true"
,那么对Server.MapPath的调用将抛出System.NotSupportedException,并显示消息"不支持给定路径的格式".