473,473 Members | 1,790 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Getting a file's ContentType

I would like to be able to get the ContentType of a file programmatically
(for example, I want *.txt files to return "text/plain"). I could not find a
way to do this using VB.NET's classes, but I am also somewhat new to using
the System.IO namespace for anything other than text files and the pure
basics, so I could very well have missed it. Any help would be appreciated.
Thanks.
--
Nathan Sokalski
nj********@hotmail.com
http://www.nathansokalski.com/
May 10 '06 #1
7 3497
Check the foll. link
http://hardrock.cnblogs.com/archive/...31/309144.html

HTH
Kalpesh

May 10 '06 #2
V
Hello Nathan,

An excellent article on codeproject may help you. Here is the link:
http://www.codeproject.com/dotnet/ContentType.asp

Regards,
Vaibhav

May 10 '06 #3

"V" <va*************@gmail.com> wrote in message
news:11**********************@i39g2000cwa.googlegr oups.com...
Hello Nathan,

An excellent article on codeproject may help you. Here is the link:
http://www.codeproject.com/dotnet/ContentType.asp

Regards,
Vaibhav


The trick mentioned works, but not always.
The safest way is to use this.
http://technolog.nl/eprogrammer/arch...12/12/415.aspx

May 10 '06 #4
The following uses Internet Explorer to find the MIME type:

[DllImport("urlmon.dll", CharSet = CharSet.Auto)]
static extern int FindMimeFromData(IntPtr pBC, IntPtr pwzUrl, byte[]
pBuffer, int cbSize,
IntPtr pwzMimeProposed, int dwMimeFlags, out IntPtr ppwzMimeOut, int
dwReserved);

/// <summary type="System.String">
/// Figures out the Content Type from a File Name
/// </summary>
/// <param name="FileName">File Name to detect</param>
/// <returns>Content Type as string</returns>
/// <remarks>The Windows API has the functionality to detect the file type
of
/// any file type registered with the Operating System. This method makes an
API
/// call to get the MIME type of the file from the
<var>FileName</var></remarks>
public string MimeTypeFromFileName(string FileName)
{
byte[] dataBytes = Encoding.ASCII.GetBytes(FileName);
if (dataBytes == null)
throw new ArgumentNullException("dataBytes");
string mimeRet = String.Empty;
IntPtr suggestPtr = IntPtr.Zero, filePtr = IntPtr.Zero, outPtr =
IntPtr.Zero;
int ret = FindMimeFromData(IntPtr.Zero, IntPtr.Zero, dataBytes,
dataBytes.Length, suggestPtr, 0, out outPtr, 0);
if (ret == 0 && outPtr != IntPtr.Zero)
{
return Marshal.PtrToStringUni(outPtr);
}
return mimeRet;
}

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Hard work is a medication for which
there is no placebo.

"Nathan Sokalski" <nj********@hotmail.com> wrote in message
news:u7**************@TK2MSFTNGP04.phx.gbl...
I would like to be able to get the ContentType of a file programmatically
(for example, I want *.txt files to return "text/plain"). I could not find
a way to do this using VB.NET's classes, but I am also somewhat new to
using the System.IO namespace for anything other than text files and the
pure basics, so I could very well have missed it. Any help would be
appreciated. Thanks.
--
Nathan Sokalski
nj********@hotmail.com
http://www.nathansokalski.com/

May 10 '06 #5
Egbert Nierop (MVP for IIS) wrote:
"V" <va*************@gmail.com> wrote in message
news:11**********************@i39g2000cwa.googlegr oups.com...
Hello Nathan,

An excellent article on codeproject may help you. Here is the link:
http://www.codeproject.com/dotnet/ContentType.asp

Regards,
Vaibhav


The trick mentioned works, but not always.
The safest way is to use this.
http://technolog.nl/eprogrammer/arch...12/12/415.aspx


Just one problem with that technique - it's undefined whether it actually
works. FindMimeFromData returns memory allocated from the heap with new[],
so there's no way to correctly free that memory unless you can be sure
you're delete[]-ing it back into the same heap.

Despite being exported from the DLL, this function really wasn't written
correctly to be used outside a known environment.

-cd
May 10 '06 #6

"Carl Daniel [VC++ MVP]" <cp*****************************@mvps.org.nospam >
wrote in message news:e1**************@TK2MSFTNGP03.phx.gbl...
Egbert Nierop (MVP for IIS) wrote:
"V" <va*************@gmail.com> wrote in message
news:11**********************@i39g2000cwa.googlegr oups.com...
Hello Nathan,

An excellent article on codeproject may help you. Here is the link:
http://www.codeproject.com/dotnet/ContentType.asp

Regards,
Vaibhav
The trick mentioned works, but not always.
The safest way is to use this.
http://technolog.nl/eprogrammer/arch...12/12/415.aspx


Just one problem with that technique - it's undefined whether it actually
works. FindMimeFromData returns memory allocated from the heap with
new[],


It uses allocated memory, in the buffer and it uses CoTaskMemAlloc, for the
mimetype string. If that were a new operator, well, I'm sure that's
compatible since the C++ new keyword, after all, just uses *the same* memory
allocator (ie HeapAlloc).
so there's no way to correctly free that memory unless you can be sure
you're delete[]-ing it back into the same heap.

That's why this declaration exists.
[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I1,
SizeParamIndex = 3)] byte[] pBuffer,
int cbSize,

if it were wrong, then MS would not support it. And besides, it never failed
in my runtime.

Despite being exported from the DLL, this function really wasn't written
correctly to be used outside a known environment.


I agree, but you might agree with me, that the whole .NET framework,
**depends** on unmanaged code, from kernel, ADSI, WMI etc, and originally,
these were never made with .NET in mind. It's the other way around, .NET was
made to interop with them. So I won't hesitate to use this code, unless you
have a proven example, that shows that it will go wrong.

Maybe a CoTaskMemAlloc would be better instead of a byte[] array, but that
won't interop with FileRead...
Here you have the generated ASM listing.
00000107 FF 75 B8 push dword ptr [ebp-48h]
0000010a 56 push esi
0000010b 6A 00 push 0
0000010d 6A 00 push 0
0000010f 8D 45 B4 lea eax,[ebp-4Ch]
00000112 50 push eax
00000113 6A 00 push 0
00000115 8B D7 mov edx,edi
00000117 33 C9 xor ecx,ecx
00000119 E8 1A 2C 86 FF call FF862D38 <-- call FindMimeFromData

and here is the IL

IL_0052: ldsfld native int [mscorlib]System.IntPtr::Zero
IL_0057: ldarg.0
IL_0058: ldloc.2
IL_0059: ldloc.0
IL_005a: ldnull
IL_005b: ldc.i4.0
IL_005c: ldloca.s V_3
IL_005e: ldc.i4.0
IL_005f: call int32 TimeStampTester.Class1::FindMimeFromData(native
int, string,uint8[], int32, string, int32, string&, int32)

As you can see, the compiler does not -worry- about packing the byte array
into something else! It just assumes, that during the Pinvoke, the memory
won't move. Now this is interesting. If I have the wrong approach, then MS
introduced a dangerous bug, by allowing us to program like this.

May 13 '06 #7

"Kevin Spencer" <ke***@DIESPAMMERSDIEtakempis.com> wrote in message
news:%2***************@TK2MSFTNGP04.phx.gbl...
The following uses Internet Explorer to find the MIME type:

[DllImport("urlmon.dll", CharSet = CharSet.Auto)]
static extern int FindMimeFromData(IntPtr pBC, IntPtr pwzUrl, byte[]
pBuffer, int cbSize,
IntPtr pwzMimeProposed, int dwMimeFlags, out IntPtr ppwzMimeOut, int
dwReserved);

/// <summary type="System.String">
/// Figures out the Content Type from a File Name
/// </summary>
/// <param name="FileName">File Name to detect</param>
/// <returns>Content Type as string</returns>
/// <remarks>The Windows API has the functionality to detect the file type
of
/// any file type registered with the Operating System. This method makes
an API
/// call to get the MIME type of the file from the
<var>FileName</var></remarks>
public string MimeTypeFromFileName(string FileName)
{
byte[] dataBytes = Encoding.ASCII.GetBytes(FileName);
if (dataBytes == null)
throw new ArgumentNullException("dataBytes");
string mimeRet = String.Empty;
IntPtr suggestPtr = IntPtr.Zero, filePtr = IntPtr.Zero, outPtr =
IntPtr.Zero;
int ret = FindMimeFromData(IntPtr.Zero, IntPtr.Zero, dataBytes,
dataBytes.Length, suggestPtr, 0, out outPtr, 0);

Hi Kevin,
outPtr leaks memory in your sample. You should free it using
CoTaskMemFree...

Cheers

May 17 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: JJ | last post by:
Hi, I am writing a cart in ASP selling downloadable files. The files are stored on remote locations i.e. http://www.thisfilestore.com/file1.zip And have different extensions, i.e. they are not...
7
by: theyas | last post by:
How can I get my code to NOT display two "Open/Save/Cancel/More Info" dialog boxes when using the "Response.WriteFile" method to download a file to IE I've asked about this before and didn't get a...
3
by: Hitesh | last post by:
Hi, I am getting the response from another Website by using the HttpHandler in my current site. I am getting the page but all the images on that page are not appearing only placeholder are...
7
by: D & J G | last post by:
Is there a way to instruct Windows file-handling - 'Opens with:' - from within VB6? I want to ensure that files with the .rtf (rich text) extension always go to Word Pad, no matter which future...
6
by: john | last post by:
The standard method to transmit a file from an aspx page to a browser is to stream the file to the response then end the response. The HTML code generated by the aspx page is discarded, and the...
5
by: mike | last post by:
Hi, I have been playing with VB.NET/C# for getting some general properties of a fileinfo object. However, FileInfo object does not seem to expose some of the basic properties like TYPE that used...
4
by: AshishMishra16 | last post by:
HI friends, I am using the Flex to upload files to server. I m getting all the details about the file, but I m not able to upload it to Server. Here is the code i m using for both flex & for...
2
by: ArwaAbood | last post by:
I want to upload file using the following code to make the form: <html> <head> <script type="text/javascript"> function redirect() { alert(msg+" want to add new file"); ...
1
by: shyaminf | last post by:
hi everybody! iam facing a problem with the transfer of file using servlet programming. i have a code for uploading a file. but i'm unable to execute it using tomcat5.5 server. kindly help me how to...
1
by: shahidrasul | last post by:
i want to download a file which user select from gridview, downloading is completing without problem but after download i want to refresh my page because i do some changes in db . but when...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.