Nave Tseva
Nave Tseva

Reputation: 878

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!

Upvotes: 0

Views: 1280

Answers (1)

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

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 (i.e. it doesn't even have one) and so you need to supply that.

Upvotes: 2

Related Questions