Getting the mime w/o using urlmon - asp.net

I was using urlmon to find the MIME of files however it didnt go well when i couldn't get the correct mime of css files and more SWFs. What can i use to get the file mime?

Hmm, I am not sure I completely understand your question, but if you want to do some sort of look up against a master list you can look at the IIS Metabase
using (DirectoryEntry directory = new DirectoryEntry("IIS://Localhost/MimeMap")) {
PropertyValueCollection mimeMap = directory.Properties["MimeMap"];
foreach (object Value in mimeMap) {
IISOle.MimeMap mimetype = (IISOle.MimeMap)Value;
//use mimetype.Extension and mimetype.MimeType to determine
//if it matches the type you are looking for
}
}

Related

How to get virtual directory physical path

As we know that a virtual direcoty can be linked to a folder with a diffrent name, how can I get the physical path of a virtual directory ?
I've been trying with HttpContext.Current.server.MapPath but it returns me the physic path plus the path I send in parameter even if the directory doesn't even exist or if it exists with a diffrent name.
Exemple :
C:\blabla\Sites\Application1\Imaageesss
- On disc
Application1\Images (In ISS, my virutal directory)
But if I do a MapPath on "/Images" it will never give me
C:\blabla\Sites\Application1\Imaageesss but
C:\inetpub\wwwroot\Images which is not the real directory linked to.
Server.MapPath("~/Images")
is the correct way to go about it as "~" references the root of your application.
This is what worked for me:
string physicalPath =
System.Web.Hosting.HostingEnvironment.MapPath(HttpContext.Current.Request.ApplicationPath);
What if you try this little snippet?
string physicalPath = HttpContext.Current.Request.MapPath(appPath);
After some more research I was able to create a method to get the physical path of a virtual IIS directory:
public static string VirtualToPhysicalPath(string vPath) {
// Remove query string:
vPath = Regex.Replace(vPath, #"\?.+", "").ToLower();
// Check if file is in standard folder:
var pPath = System.Web.Hosting.HostingEnvironment.MapPath("~" + vPath);
if (System.IO.File.Exists(pPath)) return pPath;
// Else check for IIS virtual directory:
var siteName = System.Web.Hosting.HostingEnvironment.ApplicationHost.GetSiteName();
var sm = new Microsoft.Web.Administration.ServerManager();
var vDirs = sm.Sites[siteName].Applications[0].VirtualDirectories;
foreach (var vd in vDirs) {
if (vd.Path != "/" && vPath.Contains(vd.Path.ToLower())) pPath = vPath.Replace(vd.Path.ToLower(), vd.PhysicalPath).Replace("/", "\\");
}
return pPath;
}
Caveat: this solution assumes that you only have a root application (Applications[0]).
The following should work just fine:
var physicalPath = HostingEnvironment.MapPath("~/MyVirtualDirectory");
This might answer your question:
http://msdn.microsoft.com/en-us/library/system.web.httprequest.physicalpath.aspx
However, I can't currently provide an example, because I have got a lot of work to do. When I'll find some time I'll send detailed information.

virtual path change

I want to change Virtual Path(The path is out of project means local system or Server.) of the file Which is save on the folder in asp.net.
Code is
DataTable dtFiles =
GetFilesInDirectory(HttpContext.Current.Server.MapPath(UPLOADFOLDER));
gv.DataSource = dtFiles;
gv.DataBind();
if (dtFiles != null && dtFiles.Rows.Count > 0)
{
double totalSize = Convert.ToDouble(dtFiles.Compute("SUM(Size)", ""));
if (totalSize > 0) lblTotalSize.Text = CalculateFileSize(totalSize);
}
private static string UPLOADFOLDER = "D:/Uploads";
And the error show "D:/Uploads is not a valid virtual path.".
If you want to get the files in a directory and you know the full path, then you don't need to use Server.MapPath(). Just use the path.
Incidentally, the path delimiter is incorrect in your code. The string "D:/Uploads" should be #"D:\Uploads" (note the leading # sign to denote a string that should be treated literally and not escaped).
Of course. You're telling your server to map path that is completely off the IIS. How is it supposed to do? If you're using a web application, try to avoid such ideas completely. Even though it is possible, it isn't a good idea because of security issues you can run into.

ASP.NET MVC Routing for files with muliple sub-directories

I need to setup a file handler to route with multiple sub directories something like tihs;
http://localhost/images/7/99/786936215595.jpg
I tried putting this in the global.asax file;
routes.Add(
"ImageRoute",
new Route("covers/{filepath}/{filename}",
new ImageRouteHandler()));
I am using the ImageHandler found in this Question, which works great if you have a single sub-directory (ie '/images/15/786936215595.jpg') but fails when you have multiple directories.
I tried setting up a wildcard and that didnt work (ie 'new Route("covers/{filepath}/*/{filename}"')
This is serving images from a large NAS (think something like 3 million images) so its not like I can just move files around.
Thanks!
Ok after much playing around and google fu I found how to make it work.
Change the route definition like this;
routes.Add(
"ImageRoute",
new Route("images/{*filepath}",
new ImageRouteHandler()));
Then put this after the default MapRoute. The important part is the "*" before the filepath, tells MVC to send anything following this as part of the filepath RouteData. So in the GetHttpHandler() method I can get the full path by using this;
string fp = requestContext.RouteData.Values["filepath"] as string;
Woot!
Can't you treat the entire path as one route parameter? Like so:
routes.Add(
"ImageRoute",
"/images/{path}",
new { controller = "Image", action = "Image" }
);
And then access the entire path in the ActionResult Image(string path) { } action method?

Is there a way to get ALL the MIME types instead of wrinting a huge case statement?

I want to populate
Response.ContentType = "text/plain";
From somewhere in the server/web/dictionary ALL possible MIME types according to file extension:
public string GetMimeType(string extension)
{
//This is what I am looking for.
}
Also, I have to rename the file (at least if going to be downloaded, so I have to know in advance if it's going to be opened or not.
You can store the mimetype when the file is uploaded ( FileUpload.PostedFile.ContentType ) and send that when the file is requested.
Umm... why? You're not going to be returning content of every possible type, are you?
Here's a list of common types: http://www.webmaster-toolkit.com/mime-types.shtml. There is no list that would include "ALL" types simply because any application vendor can create a custom one and associate it with a custom extension.
It's going to depend on your platform. Here's one for C# and IIS: http://blog.crowe.co.nz/archive/2006/06/02/647.aspx
In Powershell it's a one-liner:
([adsi]"IIS://localhost/MimeMap").MimeMap
The code in the link posted by Richard:
// Maintain a sorted list to contain the MIME Types
SortedList sl = new SortedList();
Console.WriteLine("IIS Mime Map - c#");
Console.WriteLine();
// Serve to connect to...
string ServerName = "LocalHost";
// Define the path to the metabase
string MetabasePath = "IIS://" + ServerName + "/MimeMap";
// Note: This could also be something like
// string MetabasePath = "IIS://" + ServerName + "/w3svc/1/root";
try
{
// Talk to the IIS Metabase to read the MimeMap Metabase key
DirectoryEntry MimeMap = new DirectoryEntry(MetabasePath);
// Get the Mime Types as a collection
PropertyValueCollection pvc = MimeMap.Properties["MimeMap"];
// Add each Mime Type so we can display it sorted later
foreach (object Value in pvc)
{
// Convert to an IISOle.MimeMap - Requires a connection to IISOle
// IISOle can be added to the references section in VS.NET by selecting
// Add Reference, selecting the COM Tab, and then finding the
// Active DS Namespace provider
IISOle.MimeMap mimetypeObj = (IISOle.MimeMap)Value;
// Add the mime extension and type to our sorted list.
sl.Add(mimetypeObj.Extension, mimetypeObj.MimeType);
}
// Render the sorted MIME entries
if (sl.Count == 0)
Console.WriteLine("No MimeMap entries are defined at {0}!", MetabasePath);
else
foreach (string Key in sl.Keys)
Console.WriteLine("{0} : {1}", Key.PadRight(20), sl[Key]);
}
catch (Exception ex)
{
if ("HRESULT 0x80005006" == ex.Message)
Console.WriteLine(" Property MimeMap does not exist at {0}", MetabasePath);
else
Console.WriteLine("An exception has occurred: \n{0}", ex.Message);
}
// Convert to an IISOle.MimeMap - Requires a connection to IISOle
// IISOle can be added to the references section in VS.NET by selecting
// Add Reference, selecting the COM Tab, and then finding the
// Active DS Namespace provider
According to my googling: (lost the links, sorry)
The "Active DS IIS Namespace Provider" is part of the IIS installation.
After you install IIS you will see that in the list of options.
If you don't see it should be located at C:\windows\system32\inetsrv\adsiss.dll.
To install IIS:
click Start, Settings, Control Panel, Add or Remove Programs, Add or Remove Windows Components, select Internet Informatoin Services (IIS).
Most of the code I've seen uses some combination of these:
using System.IO;
using System.DirectoryServices; // Right-click on References, and add it from .NET
using System.Reflection;
using System.Runtime.InteropServices;
using System.Collections;
using IISOle;
using System.Collections.Specialized;
The Active DS Namespace might be under the COM tab when adding the reference.
I've written a small class based on the webmaster-toolkit.com list. This is to avoid using COM and the IIS route or any IIS references.
It uses an XML serialized list which contains about 400 mimetypes, so is usually more than enough unless you have really obscure mimetypes. In that case you can just add to the XML file.
The full solution can be found here. Here's a sample:
class Program
{
static void Main(string[] args)
{
var list = MimeType.Load();
MimeType mimetype = list.FirstOrDefault(m => m.Extension == "jpg");
}
}

Add filter to FileUpload Control

How to add filter to the fileupload control in asp.net? I want a filter for Word Template File (.dot).
You could also do a javascript alternative to filtering it server side (you'd probably want to do that as well) but this saves the client from spending the time waiting on an upload to finish just to find out it was the wrong type.
http://javascript.internet.com/forms/upload-filter.html
So basically you just run a javascript function on submit that parses off the extension of the uploaded file and gives them an alert if its not of the right type.
You could also use document.forms[0].submit(); instead of passing the form reference through (as ASP.NET really only uses a single form (unless your doing something funky))
string fileName = fuFiles.FileName;
if(fileName.Contains(".dot"))
{
fuFiles.SaveAs(Server.MapPath("~/Files/" + fileName));
}
If you mean to filter the file extensions client/side, with the standard browser's file selector, isn't possible.
To do that you have to use a mixed type of upload, such as SWFUpload, based on a flash uploader system (that's a really nice techinque: it allows you to post more than a file at time).
The only thing you can do in standard mode is to filter the already posted file, and I suggest to use System.IO.Path namespace utility:
if (Path.GetExtension(upFile.FileName).ToUpper().CompareTo(".DOT") == 0)
{
/* do what you want with file here */
}
Check the filename of the uploaded file serverside:
FileUpload1.PostedFile.FileName
Unless you want to use java or something similar on the client, there's really not much you can do for filtering uploaded files before they're sent to the server.
Here I have a small method that I used to filter which types of files can be uploaded by the fileupload control named fuLogo.
if (fuLogo.HasFile)
{
int counter = 0;
string[] fileBreak = fuLogo.FileName.Split(new char[] { '.' });
logo = Server.MapPath("../Images/Logos/" + fileBreak[0] + counter.ToString()+ "." + fileBreak[1]);
if (fileBreak[1].ToUpper() == "GIF" || fileBreak[1].ToUpper() == "PNG")
{
while (System.IO.File.Exists(logo))
{
counter++;
logo = Server.MapPath("../Images/Logos/" + fileBreak[0] + counter.ToString() + "." + fileBreak[1]);
}
}
else
{
cvValidation.ErrorMessage = "This site does not support any other image format than .Png or .Gif . Please save your image in one of these file formats then try again.";
cvValidation.IsValid = false;
}
fuLogo.SaveAs(logo);
}
basically, I first Iterates through the directory to see if a file already exists. Should the file exist, (example picture0.gif) , it will increase the counter (to picture1.gif). It prevents that different users will overwrite each other's pictures should their pictures have the same name.

Resources