0

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#

Ramesh
  • 1
  • 3

2 Answers2

0

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;
}
NaveenBhat
  • 3,248
  • 4
  • 35
  • 48
  • ya i checked the file extension also but i need to check file content type is text or not .. bcoz suppose i changed the other file and saved .txt format know.. thats why i need to check content – Ramesh Aug 17 '12 at 07:02
  • In that case, are you looking for any specific text from the file? – NaveenBhat Aug 17 '12 at 07:15
  • yes i uploaded only txt format file only suppose somebody edit the other file and save as .txt file know that time i need to give error msg .. – Ramesh Aug 17 '12 at 07:22
0

Try this (got it from a similar question):

string contentType = FileUpload1.PostedFile.ContentType
Community
  • 1
  • 1
Dmitriy
  • 1,852
  • 4
  • 15
  • 33