C# 从物理路径转换为虚拟路径
我有一个函数,它以字节数组和文件路径的形式获取文件数据。我得到的错误是当它试图在代码bewlo中设置fileInfo时。它表示“给定物理路径,期望虚拟路径”C# 从物理路径转换为虚拟路径,c#,asp.net,C#,Asp.net,我有一个函数,它以字节数组和文件路径的形式获取文件数据。我得到的错误是当它试图在代码bewlo中设置fileInfo时。它表示“给定物理路径,期望虚拟路径” public override void WriteBinaryStorage(byte[] fileData, string filePath) { try { // Create directory if not exists. System.IO
public override void WriteBinaryStorage(byte[] fileData, string filePath)
{
try
{
// Create directory if not exists.
System.IO.FileInfo fileInfo = new System.IO.FileInfo(System.Web.HttpContext.Current.Server.MapPath(filePath)); //when it gets to this line the error is caught
if (!fileInfo.Directory.Exists)
{
fileInfo.Directory.Create();
}
// Write the binary content.
System.IO.File.WriteAllBytes(System.Web.HttpContext.Current.Server.MapPath(filePath), fileData);
}
catch (Exception)
{
throw;
}
}
调试时,提供文件路径为“E:\\WEBS\\webapp\\default\\images\\mains\\myimage.jpg”
。错误消息是
'E:/WEBS/webapp/default/images/mains/myimage.jpg' is a physical path, but a virtual path was expected.
此外,触发这种情况的是以下调用
properties.ResizeImage(imageName, Configurations.ConfigSettings.MaxImageSize, Server.MapPath(Configurations.EnvironmentConfig.LargeImagePath));
如果您已经有一个物理路径,那么调用
Server.MapPath
是没有意义的
您正在调用
MapPath
两次。我认为您的项目位于:
E:\WEBS\\webapp\
你应该尝试使用相对的参考来参考你的图片,例如
..\default\images\mains\myimage.jpg
工作:
string[] filesPath = Directory.GetFiles(Server.MapPath("~/txtPath/"));
foreach (string path in filesPath)
{
FileInfo fi = new FileInfo(path); //This Is Working
string LastAcceTime = fi.LastWriteTime; //Return Correct Value
}
不工作:
string[] filesPath = Directory.GetFiles(Server.MapPath("~/txtPath/"));
foreach (string path in filesPath)
{
FileInfo fi = new FileInfo(Server.MapPath(path)); //This Is Worng
string LastAcceTime = fi.LastWriteTime; //Return 1/1/1601
}
不要使用
Server.Mappath
两次我可以知道为什么我是C#的新手吗。请考虑一下,您是否了解MapPath
的作用以及您的代码试图做什么?这是现有的代码,不是我写的。。我的理解是MapPath是一个将虚拟路径转换为服务器路径的函数,但我还是一个新手,我可能忽略了显而易见的东西。我来这个论坛是想问一个我不确定的问题,但我并不粗鲁。没有必要否决投票。。我想这就是论坛的目的不?另一方面,我会一个接一个地投反对票,仅仅因为这太糟糕了。一旦你调用它一次,再调用它就没有意义了。代码和错误信息都很清楚,你应该已经意识到了。好的,谢谢你,现在更清楚了。。感谢您的耐心谢谢,所以我不应该使用Server.MapPath,我应该替换这行代码做什么?有时候,发现愚蠢的错误是非常简单的。非常感谢