Question

I have an issue with using FileStream to retrieve and use audio binary from Sql server database. I tried MemoryStream but wasn't working. Here's my codes for inserting the audio binary to the database using windows form.

        try
        {
            SqlCommand cmd = null;
            SqlParameter param = null;

            cmd = new SqlCommand("INSERT INTO Audio(audioBinary) VALUES(@BLOBPARAM)", conn);

            FileStream fs = null;
            fs = new FileStream("..\\..\\audio\\a3.mp3", FileMode.Open, FileAccess.Read);
            Byte[] blob = new Byte[fs.Length];
            fs.Read(blob, 0, blob.Length);
            fs.Close();

            param = new SqlParameter("@BLOBPARAM", SqlDbType.VarBinary, blob.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, blob);
            cmd.Parameters.Add(param);
            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();

            MessageBox.Show("Successful");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

The code above worked perfectly fine, the problem occurs in retrieving and using the data at Windows Phone 7 Application. Addition, the data were retrieved from web service. This is my code for retrieving the binary data.

Assuming me1 is a MediaElement, the binary data is stored inside testImage.

        ArrayOfBase64Binary testImage = new ArrayOfBase64Binary();
        byte[] audioArr = new byte[1];
        FileStream fs = null;

        audioArr = testImage[0];
        text.Text = audioArr[0].ToString();

        fs.Write(audioArr, 0, audioArr.Length);

        me1.SetSource(fs);
        me1.Play();

I tried displaying the binary data in a TextBlock and it did return an integer but when trying to write it into the stream, an error occurred:

An unhandled exception of type 'System.NullReferenceException' occurred in test.dll

Was it helpful?

Solution

FileStream fs = null;

....

fs.Write(audioArr, 0, audioArr.Length);

You will get a NullReferenceException if you try to use a FileStream object that hasn't been allocated yet. Create a new FileStream object, before trying to write to it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top