How to check the downloaded csv file or not using the content content property (without checking the extension) of file upload control in C #?

I need to check if the csv file is uploaded or not by checking the file extension. Using the filecontent property, I cannot find this type efficiently if the non-CSV file is renamed to the .csv extension. I need to prevent such things.

Anyone please suggest a method to search for the content type by reading the header information.

+5
source share
2 answers

I tried the following code that reads the first 256 bytes from a file and returns the mime type of the file using the internal dll (urlmon.dll) ..

System.Runtime.InteropServices; ...

[DllImport(@"urlmon.dll", CharSet = CharSet.Auto)]
private extern static System.UInt32 FindMimeFromData(
    System.UInt32 pBC,
    [MarshalAs(UnmanagedType.LPStr)] System.String pwzUrl,
    [MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer,
    System.UInt32 cbSize,
    [MarshalAs(UnmanagedType.LPStr)] System.String pwzMimeProposed,
    System.UInt32 dwMimeFlags,
    out System.UInt32 ppwzMimeOut,
    System.UInt32 dwReserverd
);

public string getMimeFromFile(string filename)
{
    if (!File.Exists(filename))
        throw new FileNotFoundException(filename + " not found");

    byte[] buffer = new byte[256];
    using (FileStream fs = new FileStream(filename, FileMode.Open))
    {
        if (fs.Length >= 256)
            fs.Read(buffer, 0, 256);
        else
            fs.Read(buffer, 0, (int)fs.Length);
    }
    try
    {
        System.UInt32 mimetype;
        FindMimeFromData(0, null, buffer, 256, null, 0, out mimetype, 0);
        System.IntPtr mimeTypePtr = new IntPtr(mimetype);
        string mime = Marshal.PtrToStringUni(mimeTypePtr);
        Marshal.FreeCoTaskMem(mimeTypePtr);
        return mime;
    }
    catch (Exception e)
    {
        return "unknown/unknown";
    }
}

, mimetype .

mimetype, ...

+1

- CSV - , CSV, , .

, TextFieldParser, Microsoft.VisualBasic.Text.

+1

All Articles