M.baty M.baty - 29 days ago 8
ASP.NET (C#) Question

how to download music with asp.net

I have an asp.net webform application. I want to have a button for downloading musics, so I write below code block :

protected void Button1_Click(object sender, EventArgs e)
{
string id_new;
id_new = Session["selectedmusicID"].ToString();
DataTable dt2 = new DataTable();
dt2 = blm.selectMusic("sel_music", Convert.ToInt32(id_new));
string test = dt2.Rows[0][9].ToString();
Response.ContentType = "application/mp3";
Response.AddHeader("Content-Disposition", dt2.Rows[0][9].ToString());
Response.TransmitFile(Server.MapPath( dt2.Rows[0][9].ToString()));
Response.End();
}


When I run this code and click on button it downloads the music.aspx page not mp3 file.I don't know what is my mistake.
Anyone can help me?

Answer

Finally I've solved my problem, as you can see in the code below... first I create a column named MusicByte to my music table in database.I stored the data of every music by file uploading in this column...

string id_new;
id_new = Session["selectedmusicID"].ToString();
DataTable dt2 = new DataTable();
dt2 = blm.selectMusic("sel_music", Convert.ToInt32(id_new));
string test = dt2.Rows[0][9].ToString();
string filename = test.Substring(9).Replace(" " , "").Replace(".mp3" , ".MP3");
byte[] buffer = (byte[])(dt2.Rows[0][10]);
Response.ContentType = "audio/mpeg";
Response.AddHeader("Content-Disposition", "Attachment;filename=" + filename);
byte[] datablock = new byte[0x1000];
long filesize;
int bytesread;
long totalsbytesread = 0;
using (Stream st = new MemoryStream(buffer))
        {
            filesize = st.Length;
            while (totalsbytesread < filesize)
            {
                if (Response.IsClientConnected)
                {
                    bytesread = st.Read(datablock, 0, datablock.Length);
                    Response.OutputStream.Write(datablock, 0, bytesread);
                    Response.Flush();
                    totalsbytesread += bytesread;
                }
            }
        }
        Response.End();

deleting spaces in filename and replice the .mp3 to .MP3 was usefull.Also this video in you tube helps me : Upload and download files to/from a SQL Server database