Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create FormFile from Stream

Tags:

c#

iformfile

I want to create a FormFile in my seed function. But I get a null reference exception. Here my code

FileStream fs = new FileStream("testfile.jpg", FileMode.Open, FileAccess.Read);
FormFile file = new FormFile(fs, 1024, fs.Length, "testfile", "testfile.jpg");
file.ContentType = "image/jpeg";

The null reference occurs when I am trying to set content type. Any Ideas what I am making wrong? Checked before with File.Exists which returns true.

like image 607
Sardoan Avatar asked Sep 03 '25 13:09

Sardoan


1 Answers

using (var stream = File.OpenRead("testfile.jpg"))
  {
     FormFile file = new FormFile(stream, 0, stream.Length, null, Path.GetFileName(stream.Name))
       {
         Headers = new HeaderDictionary(),
         ContentType = "image/jpeg"
       };
}

Did the jobs. Seems FormFile needs an opened stream.Found the solution here: How to instantiate an instance of FormFile in C# without Moq?

like image 62
Sardoan Avatar answered Sep 05 '25 14:09

Sardoan