2013-06-12 123 views
0

我有下面的C#代碼:重命名上傳的文件名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-」 +用戶ID,我試圖在發表評論,但它沒不工作,我如何重命名上傳的文件名?

希望得到幫助,謝謝!

+3

的SQL注入概率... –

+2

'但它沒有工作...' - 什麼** **沒有發生? –

+3

我的電子郵件是''; DROP TABLE向tblUsers;' –

回答

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 ...,這是很明顯的,因爲你不設置它的延伸。文件字節可能就好了,它只是操作系統的一個未被識別的擴展名(即它甚至沒有),所以你需要提供它。

+0

非常感謝yuo,現在我明白了! –

+0

@NaveTseva,沒問題,我很高興我可以幫助! –