C# - Check if File is Text Based

后端 未结 6 792
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-29 09:19

How can I test whether a file that I\'m opening in C# using FileStream is a \"text type\" file? I would like my program to open any file that is text based, for example, .t

6条回答
  •  旧时难觅i
    2020-11-29 10:17

    I have a below solution which works for me.This is general solution which check all types of Binary file.

         /// 
         /// This method checks whether selected file is Binary file or not.
         ///      
         public bool CheckForBinary()
         {
    
                 Stream objStream = new FileStream("your file path", FileMode.Open, FileAccess.Read);
                 bool bFlag = true;
    
                 // Iterate through stream & check ASCII value of each byte.
                 for (int nPosition = 0; nPosition < objStream.Length; nPosition++)
                 {
                     int a = objStream.ReadByte();
    
                     if (!(a >= 0 && a <= 127))
                     {
                         break;            // Binary File
                     }
                     else if (objStream.Position == (objStream.Length))
                     {
                         bFlag = false;    // Text File
                     }
                 }
                 objStream.Dispose();
    
                 return bFlag;                   
         }
    

提交回复
热议问题