How do I handle file uploads/downloads

In C#, handling file uploads and downloads can be done through ASP.NET applications, allowing you to manage files effectively. This process involves using `HttpPostedFileBase` for uploads and the `HttpResponse` for downloads.

For file uploads, you'll typically use a form to select files, which are then processed on the server side. For downloads, you can send the file back to the client using an appropriate content type and headers.

Example Code for File Upload

// This example demonstrates a simple file upload handling in an ASP.NET MVC application. [HttpPost] public ActionResult Upload(HttpPostedFileBase file) { if (file != null && file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName); var path = Path.Combine(Server.MapPath("~/UploadedFiles"), fileName); file.SaveAs(path); ViewBag.Message = "File uploaded successfully!"; } return View(); }

Example Code for File Download

// A simple example demonstrating file download in ASP.NET MVC. public ActionResult Download(string fileName) { var path = Path.Combine(Server.MapPath("~/UploadedFiles"), fileName); byte[] fileBytes = System.IO.File.ReadAllBytes(path); return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); }

file upload file download C# file handling ASP.NET file management HttpPostedFileBase