![](/img/trans.png)
[英]C# HttpRequestMessage Content-Type force as "application/json" only
[英]how to check content-type/application text in c#
我使用此代碼檢查內容類型:
字符串fileSize = FileUpload1.PostedFile.ContentType;
但是,如果我將其他文件保存為.txt格式,則表示允許。
如何在C#中檢查原始文本文件
如果我了解您的問題解答,那么您正在尋找驗證發布的文件類型的方法。 如果是這樣,則可以檢查文件擴展名。
if(FileUpload1.PostedFile.FileName.ToLowerInvariant().EndsWith(".txt"))
{
// Do stuffs
}
更新注釋:如果文件出現故障,則可以使用以下方法來驗證它是否為二進制文件; 如果不是,您可以將其視為文本文件。 好吧,為了使用此方法,您需要臨時保存文件或需要更改方法,以便可以直接從流中讀取文件。
注意:此方法不能為您提供100%的准確結果。 但是,您可以期望70-80%。 這是此代碼的源鏈接 。
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.