我不知道如何讓 cmd 顯示用戶是否輸入了正確的影像檔案路徑。我知道我必須安慰。???但我不知道如何寫出來。
設定:
- 用戶輸入他們的檔案路徑
- CMD 獲取該資訊并告訴他們它是否是影像檔案(0xFFD8 檔案)
- 然后 CMD 創建一個 .CSV 檔案,其中包含檔案路徑、檔案型別和 MD5 哈希
我堅持讓 cmd 告訴用戶它是否是 jpg 檔案。
知道我的代碼哪里出錯了嗎?
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter your file path location:");
string mainFile = MainFileInput();
Console.WriteLine("Let's determine what type of file this is:");
string typeFile = ImageType();
}
public static string MainFileInput()
{
string mainFile = Console.ReadLine();
while (File.Exists(mainFile) == false)
{
Console.WriteLine("Main file does not exist. Please enter another file: ");
mainFile = Console.ReadLine();
}
Console.WriteLine("File exists.");
return mainFile;
}
public static ImageType HeaderType(string typefile)
{
string checkType;
byte[] headerBytes;
using (FileStream fileStream = new FileStream(typefile, FileMode.Open))
{
const int mostBytesNeeded = 11;//For JPEG
if (fileStream.Length < mostBytesNeeded)
return ImageType.Unknown;
headerBytes = new byte[mostBytesNeeded];
fileStream.Read(headerBytes, 0, mostBytesNeeded);
}
if (headerBytes[0] == 0xFF &&//FF D8)
{
return ImageType.JPEG;
}
return ImageType.Unknown;
}
public enum ImageType
{
Unknown,
JPEG,
}
}
uj5u.com熱心網友回復:
您需要使用您的檔案名呼叫該方法( - 在您HeaderType(...)從呼叫該方法收到它之后)。MainmainFileMainFileInput(...)
from 的回傳值HeaderType(...)將是 type ImageType。您可以使用方法
轉換為字串后列印它。.ToString()
所以你的完整Main將是這樣的:
static void Main(string[] args)
{
Console.WriteLine("Please enter your file path location:");
string mainFile = MainFileInput();
Console.WriteLine("Let's determine what type of file this is:");
ImageType theType = HeaderType(mainFile);
Console.WriteLine("Image type: " theType.ToString());
}
uj5u.com熱心網友回復:
使用 C# 確定檔案是否為影像。
static void Main(string[] args)
{
Console.WriteLine("Please enter your file path location:");
string mainFile = MainFileInput();
Console.WriteLine("Let's determine what type of file this is:");
boolean ispic = IsPicture(mainFile);
if(ispic == true)
{
Console.WriteLine("The file is a jpg image");
}
}
public static string MainFileInput()
{
string mainFile = Console.ReadLine();
while (File.Exists(mainFile) == false)
{
Console.WriteLine("Main file does not exist. Please enter another file: ");
mainFile = Console.ReadLine();
}
Console.WriteLine("File exists.");
return mainFile;
}
private static bool IsPicture(string filePath)//filePath is the full path of the file
{
try
{
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader reader = new BinaryReader(fs);
string fileClass;
byte buffer;
byte[] b=new byte[2];
buffer = reader.ReadByte();
b[0] = buffer;
fileClass = buffer.ToString();
buffer = reader.ReadByte();
b[1]=buffer;
fileClass = buffer.ToString();
reader.Close();
fs.Close();
if (fileClass == "255216 ")//255216 is jpg; 7173 is gif; 6677 is BMP, 13780 is PNG; 7790 is exe, 8297 is rar
{
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/514726.html
