In this article I will explain with an example, how to save BYTE Array to audio file (MP3) in ASP.Net MVC.
Note: For beginners in ASP.Net MVC, please refer my article ASP.Net MVC Hello World Tutorial with Sample Program example.
 
 

Audio File Location

The sample audio file (MP3) is located inside the Files Folder (Directory) of ASP.Net MVC project.
ASP.Net MVC: Save Byte Array to MP3
 
 

Controller

The Controller consists of following Action methods.

Action method for handling GET operation

Inside this Action method, simply the View is returned.
 

Action method for handling POST operation

Inside this Action method, the BYTE Array of the sample audio file (MP3) is determined using ReadAllBytes method of the File class.
Then, the BYTE Array is saved to another audio file (MP3) using WriteAllBytes method of File class and the audio file (MP3) is created inside the Files Folder (Directory).
Finally, the success message is set into a ViewBag object and the View is redirected Index Action method.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
 
    public ActionResult Save()
    {
        // Converting the file to Byte Array.
        byte[] bytes = System.IO.File.ReadAllBytes(Server.MapPath("~/Files/Sample.mp3"));
 
        // Saving Byte Array to mp3.
        System.IO.File.WriteAllBytes(Server.MapPath("~/Files/Welcome.mp3"), bytes);
 
        // Showing message.
        ViewBag.Message = "File have been saved.";
 
        return View("Index");
    }
}
 
 

View

HTML Markup

The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Save.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The Form consists of a Submit Button.

Submitting the Form

When the Submit Button is clicked, the ViewBag object is checked for NULL and if it is not NULL then the value of the ViewBag object is displayed using JavaScript Alert Message Box.
@{
     Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @using (Html.BeginForm("Save", "Home", FormMethod.Post))
    {
        <input id="btnSave" type="submit" value="Save" />
    }
    @if (ViewBag.Message != null)
    {
        <script type="text/javascript">
            window.onload = function () {
                alert("@ViewBag.Message");
            };
        </script>
    }
</body>
</html>
 
 

Screenshot

ASP.Net MVC: Save Byte Array to MP3
 
 

Downloads