Wednesday, January 21, 2009

C#: upload Audio Files in Sql Server

Code to upload Audio/Image Files in Sql Server


protected void Button1_Click(object sender, EventArgs e)
{
Int32 intAudioSize = 0;
string strAudioType = null;
Stream AudioStream = null;

// Gets the Size of the Audio
intAudioSize = FileUpload1.PostedFile.ContentLength;

// Gets the Audio Type
strAudioType = FileUpload1.PostedFile.ContentType;

// Reads the Audio
AudioStream = FileUpload1.PostedFile.InputStream;

byte[] AudioContent = new byte[intAudioSize + 1];
int intStatus = 0;
intStatus = AudioStream.Read(AudioContent, 0, intAudioSize);

// Create Instance of Connection and Command Object
SqlConnection myConnection = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
SqlCommand myCommand = new SqlCommand("Insert into AudioTable (Audio,AudioType) Values (@Audio,@AudioType)", myConnection);

// Mark the Command as a SPROC/Query
myCommand.CommandType = CommandType.Text;

// Add Parameters to SPROC
SqlParameter prmAudio = new SqlParameter("@Audio", SqlDbType.Image);
prmAudio.Value = AudioContent;
myCommand.Parameters.Add(prmAudio);

SqlParameter prmAudioType = new SqlParameter("@AudioType", SqlDbType.VarChar, 255);
prmAudioType.Value = strAudioType;
myCommand.Parameters.Add(prmAudioType);

try
{
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
Response.Write("New audio file uploaded successfully!");
}
catch (SqlException SQLexc)
{
Response.Write("Insert Failed. Error Details are: " + SQLexc.ToString());
}
}

No comments:

Post a Comment