C# - Check if File is Text Based

后端 未结 6 793
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  情书的邮戳
    2020-11-29 09:59

    To get the real type of a file, you must check its header, which won't be changed even the extension is modified. You can get the header list here, and use something like this in your code:

    using(var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
    {
       using(var reader = new BinaryReader(stream))
       {
         // read the first X bytes of the file
         // In this example I want to check if the file is a BMP
         // whose header is 424D in hex(2 bytes 6677)
         string code = reader.ReadByte().ToString() + reader.ReadByte().ToString();
         if (code.Equals("6677"))
         {
            //it's a BMP file
         }
       }
    }
    

提交回复
热议问题