0

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

Community
  • 1
  • 1
jpo
  • 3,959
  • 20
  • 59
  • 102

1 Answers1

0

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.
Snixtor
  • 4,239
  • 2
  • 31
  • 54
  • Thanks for your input. I am using an html file uploader to upload and display uploaded files. As you know, for security purposes, the path of the file is not shown when I simply display an existing path. Unfortunately, when looping through the files, the look does not seem to read the files that were preloaded in the file uploader. So far, I read the files using an HttpPostedFileBase So having the path, I was looking for a way to initialize the httppostedfilebase that is read by the loop. – jpo Jan 17 '13 at 01:02
  • So you're saying you have a loop that displays a list of file names, based on a collection of HttpPostedFileBase instances? Why not just change the loop to take a list of file names as input? – Snixtor Jan 17 '13 at 01:09
  • I will give that a try. I have a view with a number of file uploaders. Some are pre-loaded with files and others are not. The loop foes through all the files to grab them. I tried Httppostedfilesbase first because most resources on the web use this file type for file uploads. – jpo Jan 17 '13 at 01:16