嗯,我终于找到了一种非常简单的方法——我想我有点想多了。我想我会分享解决方案,因为你们中的一些人可能需要它。我测试了它,它对我有用。
您只需要继承自HttpPostedFileBase 的create your own class HttpPostedFileBaseDerived。它们之间的唯一区别是你可以在那里创建一个构造函数。
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 对象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 回复到HttpPostedFileBase,这样您就不必更改您已有的任何其他代码。
希望这对将来的任何人都有帮助。还要感谢 Manoj Choudhari 的回答,感谢我知道在哪里不寻找解决方案。