有没有办法重命名上传的文件而不保存?

问题描述 投票:0回答:2

我试着调查other solutions,但他们建议:

  1. save the filesaveAs()有不同的名字
  2. once the file is savedMove()更改文件名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或其他任何方式做到这一点?感谢您的帮助,感谢您花时间阅读本文。 :)

c# asp.net memorystream
2个回答
1
投票

简答:没有

长答案:只有文件系统中存在文件时,才能重命名文件。

上传的文件根本不是文件 - 当您使用Request.Files访问它们时。他们是溪流。由于相同的原因,fileName属性是只读的。

没有与流关联的名称。

根据文档,FileName属性

获取客户端上文件的完全限定名称。


0
投票

好吧,我终于找到了一种非常简单的方法 - 我想我有点过分思考了这一点。我想我会分享解决方案,因为有些人可能需要它。我测试了它,它对我有用。

你只需要继承create your own classHttpPostedFileBaseDerived 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的回答,感谢我了解到哪里不寻找解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.