简体   繁体   中英

how to check content-type/application text in c#

i used this code for checking the content type :

string fileSize = FileUpload1.PostedFile.ContentType;

but if i save the other file in .txt format means ,it will allowed.

how will check the orginal text file or not in c#

If I understand your problem propelry, you are looking for validating the posted file type. If so, then you can check the file extension.

if(FileUpload1.PostedFile.FileName.ToLowerInvariant().EndsWith(".txt"))
{
     // Do stuffs
}

Update for comments: If the file is malfunctioned, then you can use below method to verify whether it is a binary file; if not you can consider it as text file. Well, in order to use this method you need to save the file temporarily or need to alter the method so that it can read directly from stream.

Note: This method don't give you 100% accurate result. However, you can expect 70-80%. Here is the source link of this code.

private bool IsBinaryFile(string filePath, int sampleSize = 10240)
{
    if (!File.Exists(filePath))
        throw  new ArgumentException("File path is not valid", filePath);

    var buffer = new char[sampleSize];
    string sampleContent;

    using (var sr = new StreamReader(filePath))
    {
        int length = sr.Read(buffer, 0, sampleSize);
        sampleContent = new string(buffer, 0, length);
    }

    //Look for 4 consecutive binary zeroes
    if (sampleContent.Contains("\0\0\0\0"))
        return true;

    return false;
}

试试看(从类似的问题中得到它):

string contentType = FileUpload1.PostedFile.ContentType

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM