Skip to content

Instantly share code, notes, and snippets.

@ankitkanojia
Last active Sep 2, 2019
Embed
What would you like to do?
Upload/Save media file using HttpPostedFileBase class in C# MVC
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
namespace YourProjectNameSpace.Helpers
{
public static class Utilities
{
public static string SaveFile(HttpPostedFileBase file, string virtualPath, string physicalPath, string filePath)
{
try
{
//Check directory exis or not
if (!Directory.Exists(physicalPath))
{
Directory.CreateDirectory(physicalPath);
}
//Check file is exist or not
if (!string.IsNullOrWhiteSpace(filePath) && File.Exists(filePath))
{
//Delete Existing file
File.Delete(filePath);
}
//Save new image and update user data
var filename = string.Concat(Guid.NewGuid(), Path.GetExtension(file.FileName));
var savePath = Path.Combine(physicalPath, filename);
file.SaveAs(savePath);
return filename;
}
catch (Exception e)
{
return string.Empty;
}
}
}
}
using ProjectNameSpace.Helpers;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace ProjectNameSpace.Controllers
{
public class SampleController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UploadFile(HttpPostedFileBase fileObject)
{
var virtualPath = StaticValues.AdvertisementImagePath;
var physicalPath = Server.MapPath(virtualPath);
Utilities.SaveFile(fileObject, virtualPath, physicalPath, "FILE PATH");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment