简体   繁体   中英

Rename the uploaded file name C#

I have the following C# code:

SelectQuery = string.Format("SELECT UserID from tblUsers WHERE Email='{0}'", Email);
ds = DbQ.ExecuteQuery("SiteDB.mdb", SelectQuery);
string UserID = ds.Tables[0].Rows[0]["UserID"].ToString();
if (Request.ContentLength != 0)
{
    int Size = Request.Files[0].ContentLength / 1024;
    if (Size <= 512)
    {
        string LocalFile = Request.Files[0].FileName;
        int LastIndex = LocalFile.LastIndexOf(@"\") + 1;
        File = LocalFile.Substring(LastIndex, LocalFile.Length - LastIndex);
   //     File = "ProfilePic-Id-" + UserID;
        string Path = Server.MapPath("images/profiles/") + File;
        Request.Files[0].SaveAs(Path);

    }
    else
    {
        Response.Write("The file is too big !");
    }
}
else
{
    Response.Write("Unknown Error !");
}

I want that the uploaded file name rename to "ProfilePic-Id-" + the UserID, I tried in the comment but it didn't work, how can I rename the uploaded file name?

Wish for help, thanks!

How about something like this:

if (Size <= 512)
{
    string path = string.Format("~/images/profiles/ProfilePic-Id-{0}.{1}",
        UserID, System.IO.Path.GetExtension(Request.Files[0].FileName));
    Request.Files[0].SaveAs(Server.MapPath(path));

}

See, when you say I get some unrecognized file ... , that's pretty obvious because you don't set an extension on it. The files bytes are likely just fine, it's just an unrecogonized extension by the OS (ie it doesn't even have one) and so you need to supply that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM