EDN Admin
Well-known member
How to detect a file is true Office file format? Could you provide a way except checking file extension?
The code as follows:
<span style="color:#666666; font-family:Segoe UI,Helvetica,Garuda,Arial,sans-serif; font-size:14px; line-height:21px private bool IsAllowedExtension(string filePath)<br/>
{<br/>
bool isAllowed = false;<br/>
System.IO.FileStream fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);<br/>
System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(fileStream);<br/>
string fileClass = "";<br/>
byte buffer;<br/>
try<br/>
{<br/>
buffer = binaryReader.ReadByte();<br/>
fileClass = buffer.ToString();<br/>
buffer = binaryReader.ReadByte();<br/>
fileClass += buffer.ToString();<br/>
}<br/>
catch<br/>
{<br/>
return false;<br/>
}<br/>
binaryReader.Close();<br/>
fileStream.Close();<br/>
String[] fileType = { "8075", "208207","4946" }; //File code 8075: Office2007; 208207:Office2003; 4946: .txt type file.<br/>
for (int i = 0; i < fileType.Length; i++)<br/>
{<br/>
if (fileClass == fileType)<br/>
{<br/>
isAllowed = true;<br/>
break;<br/>
}<br/>
}<br/>
return isAllowed;<br/>
}
The up solution works fine if the file content is not null. But it will catch an exception if the content of current file is null because the "<span style="color:#666666; font-family:Segoe UI,Helvetica,Garuda,Arial,sans-serif; font-size:14px; line-height:21px buffer
= binaryReader.ReadByte();" is 0.
How to deal with this issue?
Thanks very much!
Edison.
<br/>
View the full article
The code as follows:
<span style="color:#666666; font-family:Segoe UI,Helvetica,Garuda,Arial,sans-serif; font-size:14px; line-height:21px private bool IsAllowedExtension(string filePath)<br/>
{<br/>
bool isAllowed = false;<br/>
System.IO.FileStream fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);<br/>
System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(fileStream);<br/>
string fileClass = "";<br/>
byte buffer;<br/>
try<br/>
{<br/>
buffer = binaryReader.ReadByte();<br/>
fileClass = buffer.ToString();<br/>
buffer = binaryReader.ReadByte();<br/>
fileClass += buffer.ToString();<br/>
}<br/>
catch<br/>
{<br/>
return false;<br/>
}<br/>
binaryReader.Close();<br/>
fileStream.Close();<br/>
String[] fileType = { "8075", "208207","4946" }; //File code 8075: Office2007; 208207:Office2003; 4946: .txt type file.<br/>
for (int i = 0; i < fileType.Length; i++)<br/>
{<br/>
if (fileClass == fileType)<br/>
{<br/>
isAllowed = true;<br/>
break;<br/>
}<br/>
}<br/>
return isAllowed;<br/>
}
The up solution works fine if the file content is not null. But it will catch an exception if the content of current file is null because the "<span style="color:#666666; font-family:Segoe UI,Helvetica,Garuda,Arial,sans-serif; font-size:14px; line-height:21px buffer
= binaryReader.ReadByte();" is 0.
How to deal with this issue?
Thanks very much!
Edison.
<br/>
View the full article