System.IO errors when accessing MP3 via filestream?

T

Tina

Hello:

When users access my page to listen to an MP3 file, I send them to an
ASPX page that does some necessary server-side database logging first
and then returns the MP3 file using the filestream object.

It works for the most part, but when I check my error logs, it's clear
not everyone is getting the MP3 because the file is "being used by
another process." Here is the error:

System.IO.IOException: The process cannot access the file "[path on my
server]\media\mp3\myaudiofile.mp3" because it is being used by another
process.
at System.IO.__Error.WinIOError(Int32 errorCode, String str)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess
access, FileShare share, Int32 bufferSize, Boolean useAsync, String
msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode)
at _ASP.index_aspx.StreamMP3()

Is there any way to eliminate the possibility of this error occurring?
Do I need to set something in the web config that allows multiple
concurrent access to the file? Or is there something I'm not closing
at the end of my filestream?

Here is my StreamMP3() function:

void StreamMP3()
{
try
{
string strString = "yes";

string strMP3File = Request.QueryString["mp3_file"];

string strMP3Url = "/media/mp3/" + strMP3File;

//New FileStream
FileStream MyFileStream;
long FileSize;

//Map the path to the .MP3 file
string strMapPath = Server.MapPath(strMP3Url);
MyFileStream = new FileStream(strMapPath, FileMode.Open);
FileSize = MyFileStream.Length;

//Allocate size for our buffer array
byte[] Buffer = new byte[(int)FileSize];
//MyFileStream.Read(Buffer, 0, (int)FileSize);

int count = 0;
int offset = 0;

while( (count = MyFileStream.Read( Buffer, offset,
Buffer.Length ) ) > 0 )
{
Response.OutputStream.Write( Buffer, offset, count );
}


//Do buffer cleanup
Response.Buffer = true;
Response.Clear();

//Add the appropriate headers
Response.AddHeader("Content-Type", "audio/mpeg");
Response.AddHeader("Content-Disposition", "attachment;filename=" +
strMP3File);

//Add the appropriate content-type
Response.ContentType = "audio/mpeg";

//Stream file via a Binary Write
Response.BinaryWrite(Buffer);
// Response.WriteFile(strMP3Url);

if (MyFileStream != null)
{
//Close the file.
MyFileStream.Close();
}

Response.End();
}
catch (System.Exception err)
{
Response.Write("I didn't see any MP3's. Try again.");
Response.Write(err.ToString());
}
}

Thanks,
Tina
 
J

Jason Hales

Try MyFileStream = new FileStream(strMapPath,
FileMode.Open,FileAccess.Read, FileShare.Read)
 
T

Tina

Jason:

You're a lifesaver! Thanks so much for pointing these additional
parameters out. They did the trick.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top