Monday, March 28, 2016

MVC File I/O



Model
   public class UserModel  
   {  
     public int Id { get; set; }  
     public string Name { get; set; }  
     public ICollection Files { get; set; }  
     public IList FileAttachments { get; set; }  
   }  
   public class FileAttachment  
   {  
     public int UserId { get; set; }  
     public string Name { get; set; }  
     public string ContentType { get; set; }  
   } 


Controller
   public class HomeController : Controller  
   {  
     private string SavePath = "C:\\TempFile";  
     public ActionResult Index()  
     {  
       var userModel = new UserModel();  
       return View(userModel);  
     }  
     [HttpPost]  
     public ActionResult Index(UserModel userModel)  
     {  
       var attachements = new List();  
       Directory.CreateDirectory(SavePath);  
       if (userModel.Files != null)  
       {  
         foreach (var file in userModel.Files)  
         {  
           // Set the name of the file to upload.  
           string extension = Path.GetExtension(file.FileName);  
           string fileName = String.Concat(DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + Guid.NewGuid(), extension);  
           //save file  
           file.SaveAs(Path.Combine(SavePath, fileName));  
           attachements.Add(new FileAttachment()  
           {  
             UserId = userModel.Id,  
             Name = fileName,  
             ContentType = file.ContentType  
           });  
         }  
         userModel.FileAttachments = attachements;  
       }  
       return View(userModel);  
     }  
     public FileResult Download(FileAttachment fileAttachment)  
     {  
       var cd = new System.Net.Mime.ContentDisposition  
       {  
         FileName = fileAttachment.Name,  
         Inline = false,  
       };  
       Response.AppendHeader("Content-Disposition", cd.ToString());  
       return File(Path.Combine(SavePath, fileAttachment.Name), fileAttachment.ContentType);  
     }  
   }  

View




http://www.dotnetperls.com/file
http://www.tutorialspoint.com/csharp/csharp_file_io.htm
http://csharp.net-tutorials.com/file-handling/reading-and-writing/

https://getjins.wordpress.com/2008/09/10/a-quick-look-at-browser-engines-trident-gecko-webkit-presto/