Search code examples
c#filepathhttppostedfilebase

C#: Initialize HttpPostedFileBase from a file path (string)


I have a path (stored as a string) - eg \\documents\doc1.txt. I am trying to initialize a variable of type HttpPostedFileBase with the file represented by the string path. How can I do that please? I have looked at method like

 Model.File[count] = File.Open(item.PictureDirectory, FileMode.Open); 

but these return System.io.filestream objects.

FileStream file = File.OpenRead(filepath);

But how can I convert this to an httppostedfilebase?

I am trying to do exactly what is posted here


Solution

  • Firstly, as in the other question link to, having a method that requires a HttpPostedFileBase as an input, and then requires you to send a file not automatically transferred as a HttpPostedFileBase, suggests you need to refactor the method. In the example by Pommy, perhaps an input of Stream would be more appropriate?

    Now, if you absolutely must have an instance of HttpPostedFileBase, here's what you're up against. The class is abstract, so you're never going to construct it directly. Instead you'll need to construct an inheriting class. Within the standard libraries, HttpPostedFileWrapper inherits, and takes HttpPostedFile as a constructor input.

    But here's the rub, the constructor for HttpPostedFile is internal, so outside of the System.Web library, you're not constructing an instance directly.

    Your options then, are:

    1. Find a factory, or some other method in System.Web that will construct a HttpPostedFile instance for you (my suspicion is you won't find that).
    2. Implement your own inheriting class of base HttpPostedFileBase. This should be simple enough, it's only a small class, and depending on your code making use of it, you might not even have to implement all methods.
    3. My recommended approach, if possible - Refactor your code to not use HttpPostedFileBase, and go with, say, Stream instead.