我试着调查other solutions
,但他们建议:
save the file
与saveAs()
有不同的名字once the file is saved
或Move()
更改文件名Copy()
在我的情况下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
对象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的回答,感谢我了解到哪里不寻找解决方案。