Search code examples
c#asp.net-mvcfileinfo

Get size of uploading file C# MVC


I'am trying create some validation for file size. My code:

    [HttpPost]
    public ActionResult Index(FotoModel model)
    {
        TryUpdateModel(model);
        if (ModelState.IsValid)
        {
            if (model != null && model.File != null)
            {
                var fileName = Path.GetFileName(model.File.FileName);
                var fileExtension = Path.GetExtension(fileName);
                long fileSize = new FileInfo(fileName).Length;
                fileName = "file" + fileExtension;
                var path = Path.Combine(Server.MapPath("~/Content/Images"), fileName);
                if (fileSize < 55000)
                {
                    model.File.SaveAs(path);
                    model.link = fileName.ToString();
                }
                else
                {
                    ViewData["Size"] = "Akceptowane pliki: jpg, jpeg, png o maksymalnym rozmiarze 50 KB";
                }

                return View(model);
            }
        }
        return View(model);
    }

And in this line:

long fileSize = new FileInfo(fileName).Length;

I'am receiving error: "File cannot be found". Do You know how can I resolved this ?


Solution

  • In Asp.Net MVC we have to use HttpPostedFileBase for Uploaded files as shown below :-

    public ActionResult Index(FotoModel model, HttpPostedFileBase file)
    {
      if (file != null)
            {
                int byteCount = file.ContentLength;  // <---Your file Size or Length
                .............
                .............
            }
    }