You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET中跨目录复制文件时遭遇ArgumentException异常求助

问题:复制文件时抛出System.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 14:40:09