1

OK... so here is something I do not even know if it is even possible. Is it possible to upload an image file during the initial phase of a code first migration? For instance, when creating an initial site user or an admin user that has a portrait image, would it be possible to upload that image during the initial creation of that user?

I couldn't find anything relevant in SO or online that would even come close to even suggest a viable solution so this might be the very first time something like this has even been attempted.

2
  • Where do you want to "upload" it? You can seed it into DB field if that's a viable solution for you. Commented Oct 10, 2017 at 19:57
  • I'd rather not "seed" it into the database rather upload it to a "repo" for all the portraits using a GUID for the image name. This is what im using in the production environment and would somehow replicate it in the migration (if even possible) Commented Oct 10, 2017 at 20:01

1 Answer 1

1
  1. First, create the new migration file (or use the existing one).
  2. Inside Up() method you can put code for file upload, and inside Down() method code for file removal from repo (in case you want to revert migration).

Below is one of the many possible ways to do some remote upload, this is one of the simplest:

using (var webClient = new WebClient()) { webClient.UploadFile("ftp://localhost/samplefile.jpg", "samplefile.jpg"); } 

For this to work you should add using System.Net; to the migration file. Also, obviously you need to handle upload permissions and credentials, depending on the type of remote repo you are using.

EDIT:

Using File object is even more trivial. Here is the complete code for migration class:

using System; using System.Data.Entity.Migrations; using System.IO; public partial class MigrationWithFileCopy : DbMigration { public override void Up() { File.Copy("sourceFile.jpg", "destinationFile.jpg"); } public override void Down() { File.Delete("destinationFile.jpg"); } } 
Sign up to request clarification or add additional context in comments.

4 Comments

I will implement this, try it and let you know. Thank you :)
Can this be used as system.io instead of system.net? like using the system file object? If possible, I would like to use server map path for the destination rather than a URI.
NICE!!! Thank you for the variant. I will test and get back to you asap.
My project just ate itself (EF puked) as soon as I can fix that, I will test this. It may be a few days.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.