【问题标题】:Is there a way to rename the uploaded file without saving it?有没有办法重命名上传的文件而不保存它?
【发布时间】:2019-02-20 17:05:30
【问题描述】:

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

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

【问题讨论】:

    标签: c# asp.net memorystream


    【解决方案1】:

    简短回答:

    长答案: 仅当文件系统上存在文件时,您才能重命名文件。

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

    没有与流相关的名称。

    根据文档,FileName 属性

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

    【讨论】:

    • 感谢您抽出宝贵的时间回复,您告诉我在哪里找不到解决方案,为我节省了很多时间 :)
    【解决方案2】:

    嗯,我终于找到了一种非常简单的方法——我想我有点想多了。我想我会分享解决方案,因为你们中的一些人可能需要它。我测试了它,它对我有用。

    您只需要继承自HttpPostedFileBasecreate 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 的回答,感谢我知道在哪里不寻找解决方案。

    【讨论】:

    • 重命名内存中的上传文件,而不浪费资源进行不必要的保存。
    • 但是你为什么要覆盖一个类呢?你不能保留一个包含所需文件名的字符串并将其传递给处理文件的方法吗?
    • 当然,您可以这样做,但在某些情况下,这样代码会变得更加混乱,因为现在您不是传递一个东西,而是传递两个。所以很高兴有一个替代方案,它不会强迫你为了重命名一些文件而强制更改整个链中的大量其他代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-26
    • 1970-01-01
    相关资源
    最近更新 更多