[英]how to check content-type/application text in c#
i used this code for checking the content type : 我使用此代码检查内容类型:
string fileSize = FileUpload1.PostedFile.ContentType; 字符串fileSize = FileUpload1.PostedFile.ContentType;
but if i save the other file in .txt format means ,it will allowed. 但是,如果我将其他文件保存为.txt格式,则表示允许。
how will check the orginal text file or not in c# 如何在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. 注意:此方法不能为您提供100%的准确结果。 However, you can expect 70-80%.
但是,您可以期望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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.