Check if file exists

Topics: ASP.NET 2.0
Jan 27, 2011 at 3:47 AM

I am using the MP3 Player extension (thanks RTUR) and it is working great.  However before I include the mp3 control into the post, I would first like to check to make sure the file exists.  

For example:

if (File.exists("/BlogEngine.NET/file.axd?file=2011%2f1%2ftest.mp3"))
// show player
else
// show user friendly message

 

However as the above link isn't an actual file reference, how does one check to see if the file exists using the "file.axd?file=...." reference

Coordinator
Jan 27, 2011 at 8:02 AM

That's true the first part of the URL (with file.axd) is not a physical location, but the 2nd part is a physical location.  You could use the code below to parse out the folder & filename from the end of that URL and then check to see if it exists.

Match m = Regex.Match("/BlogEngine.NET/file.axd?file=2011%2f1%2ftest.mp3", "/file\\.axd\\?file=(.*)$", RegexOptions.IgnoreCase);
if (m.Success)
{
	string folderAndFile = HttpUtility.UrlDecode(m.Groups[1].Value);
	if (!string.IsNullOrEmpty(folderAndFile))
	{
		string fullPath = System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/files/" + folderAndFile);
		if (File.Exists(fullPath))
		{ 
			// show player
		}
	}
}