ASP.NET中跨目录复制文件时遭遇ArgumentException异常求助
原代码
string tempKYCFolderPath = "~/Attachments/KYC/KYCTemp/"; string zipfolder = tempKYCFolderPath + "Userdata/"; DirectoryInfo tempPoposalFolder = new DirectoryInfo(HostingEnvironment.MapPath(zipfolder)); if (!tempPoposalFolder.Exists) { tempPoposalFolder.Create(); } string tempUserFolderPath = Path.Combine(tempPoposalFolder.FullName, dr["User Id"] + "_" + dr["Name"].ToString().Trim()); string fileNameAppend = "kyc_" + dr["User Id"].ToString(); DirectoryInfo tempUserFolder = new DirectoryInfo(tempUserFolderPath); if (!tempUserFolder.Exists) { tempUserFolder.Create(); } if (dr["PassportFile"] != DBNull.Value) { FileInfo file = new FileInfo(HostingEnvironment.MapPath(Path.Combine(tempKYCFolderPath, dr["PassportFile"].ToString()))); if (file != null && file.Exists) { file.CopyTo(HostingEnvironment.MapPath(Path.Combine(tempUserFolderPath , fileNameAppend + "PassportFile" + file.Extension)), true); } }
错误信息
System.ArgumentException
HResult=0x80070057
消息:相对虚拟路径'C:/eureeca/solution_Ap3/Attachments/KYC/KYCTemp/Userdata/7_aseel amas amassi/kyc_7PassportFile.jpg'在此处不被允许。
Source=App_Web_jtqcbvoc堆栈跟踪:
at Crowd_funding_pages_Admin_UserNiNList.ExporttoCsv(String userid) in c:\eureeca\solution_Ap3\Crowd-funding-pages\Admin\UserNiNList.aspx.cs:line 139此异常最初在以下调用堆栈中抛出:
[外部代码]
Crowd_funding_pages_Admin_UserNiNList.ExporttoCsv(string) in UserNiNList.aspx.cs
问题原因
错误出在file.CopyTo这一行:tempUserFolderPath已经是通过HostingEnvironment.MapPath转换得到的物理路径,但你再次把它传给HostingEnvironment.MapPath——这个方法仅接受虚拟路径(如~/xxx格式),传入物理路径会直接触发ArgumentException。
修复方案
直接用物理路径组合目标文件路径,无需再调用HostingEnvironment.MapPath:
修改关键行代码:
file.CopyTo(Path.Combine(tempUserFolderPath , fileNameAppend + "PassportFile" + file.Extension), true);
修正后的核心代码段
if (dr["PassportFile"] != DBNull.Value) { FileInfo file = new FileInfo(HostingEnvironment.MapPath(Path.Combine(tempKYCFolderPath, dr["PassportFile"].ToString()))); if (file != null && file.Exists) { string targetFilePath = Path.Combine(tempUserFolderPath, fileNameAppend + "PassportFile" + file.Extension); file.CopyTo(targetFilePath, true); } }
内容的提问来源于stack exchange,提问作者DHRUV Mistry

