上传图像时DirectoryNotFoundException

时间:2018-03-07 20:11:17

标签: c# asp.net-mvc

在此代码中,将文件保存到磁盘时会发生错误。

if (ModelState.IsValid)
{
    if (account.file != null)
    {
        string FileName = Path.GetFileName(account.file.FileName);
        //Save files to disk
        account.file.SaveAs(Server.MapPath("Uploads/" + FileName));

        //Add Entry to DataBase
        string conection = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(conection))
        {

            string InsertAccount = "Insert into tblUser (FirstName,LastName,EmailAdress,UserName,Password,UserImage) values(@fname,@lname,@emailadress,@username,@password,@Userimagepath)";
            SqlCommand cmd = new SqlCommand(InsertAccount, con);
            cmd.Parameters.AddWithValue("@fname", account.FirstName);
            cmd.Parameters.AddWithValue("@lname", account.LastName);
            cmd.Parameters.AddWithValue("@emailadress", account.EmailAddress);
            cmd.Parameters.AddWithValue("@username", account.Username);
            cmd.Parameters.AddWithValue("@password", account.Password);
            cmd.Parameters.AddWithValue("@UserimagePath", "Uploads/" + FileName);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }

    }
}

无法找到路径E:\Projects\FBClone\FBClone\Account\Uploads\14494605_1912172235673452_6934911680009623037_n.jpg的一部分。 描述:执行当前Web请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

异常详细信息:System.IO.DirectoryNotFoundException:找不到路径E:\Projects\FBClone\FBClone\Account\Uploads\14494605_1912172235673452_6934911680009623037_n.jpg的一部分。

来源错误:

Line 30: string FileName = Path.GetFileName(account.file.FileName);
Line 31: //Save files to disk
Line 32: account.file.SaveAs(Server.MapPath("Uploads/" + FileName));
Line 33: 
Line 34: //Add Entry to DataBase

源文件:E:\ Projects \ FBClone \ FBClone \ Controllers \ AccountController.cs行:32

1 个答案:

答案 0 :(得分:0)

查看this SO link,您似乎需要在上传前面使用代字号

account.file.SaveAs(Server.MapPath("~Uploads/" + FileName));