[英]Is there a way to rename the uploaded file without saving it?
我嘗試研究other solutions
,但是他們建議:
saveAs()
用不同的名稱save the file
Move()
或Copy()
once the file is saved
文件once the file is saved
更改文件名 就我而言, I need to rename it without saving it
。 我嘗試更改file.FileName
屬性,但是它是ReadOnly
。
我想要得到的結果是:
public HttpPostedFileBase renameFiles(HttpPostedFileBase file)
{
//change the name of the file
//return same file or its copy with a different name
}
這將是good to have
HttpPostedFileBase
的return type
,但是它can be sacrificed
如果需要的話。
有沒有辦法通過memory streams
或其他方式做到這一點? 感謝您的幫助,感謝您抽出寶貴的時間閱讀本文檔。 :)
簡短答案:否
長答案:僅當文件系統上存在文件時,才可以重命名文件。
上載的文件根本不是文件-當您使用Request.Files訪問它們時。 他們是溪流。 由於相同的原因,fileName屬性為只讀。
沒有與流關聯的名稱。
根據文檔,FileName屬性
獲取客戶端上文件的標准名稱。
好吧,我終於找到了一種非常簡單的方法-我想我對此有點想過。 我想我將只分享解決方案,因為其中一些人可能需要它。 我測試了它,對我有用。
你只需要create your own class
HttpPostedFileBaseDerived
從繼承HttpPostedFileBase
。 它們之間的唯一區別是您可以在那里創建一個構造函數。
public class HttpPostedFileBaseDerived : HttpPostedFileBase
{
public HttpPostedFileBaseDerived(int contentLength, string contentType, string fileName, Stream inputStream)
{
ContentLength = contentLength;
ContentType = contentType;
FileName = fileName;
InputStream = inputStream;
}
public override int ContentLength { get; }
public override string ContentType { get; }
public override string FileName { get; }
public override Stream InputStream { get; }
public override void SaveAs(string filename) { }
}
}
由於constructor is not affected by ReadOnly
,因此您可以輕松地copy in the values from your original file
對象copy in the values from your original file
to
derived class's instance
,同時也將新名稱放入其中:
HttpPostedFileBase renameFile(HttpPostedFileBase file, string newFileName)
{
string ext = Path.GetExtension(file.FileName); //don't forget the extension
HttpPostedFileBaseDerived test = new HttpPostedFileBaseDerived(file.ContentLength, file.ContentType, (newFileName + ext), file.InputStream);
return (HttpPostedFileBase)test; //cast it back to HttpPostedFileBase
}
完成后,您可以type cast
其type cast
HttpPostedFileBase
回HttpPostedFileBase
這樣就不必更改任何其他已有的代碼。
希望這對將來的任何人有幫助。 同時還要感謝Manoj Choudhari的回答,也要感謝我了解到哪里不尋求解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.