重命名上传的文件名C#

时间:2013-06-12 16:56:57

标签: c# .net file-upload

我有以下C#代码:

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 !");
}

我希望上传的文件名重命名为“ProfilePic-Id-”+ UserID,我在评论中尝试但是它不起作用,如何重命名上传的文件名?

希望得到帮助,谢谢!

1 个答案:

答案 0 :(得分:2)

这样的事情怎么样:

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));

}

当你说I get some unrecognized file ...时,请注意,这很明显,因为你没有设置扩展名。文件字节可能很好,它只是操作系统的一个未经识别的扩展(即它甚至没有),所以你需要提供它。