如果連接了多個USB設備(至少一個包含密鑰),下面的代碼將返回false。.NET應用程序中的c#代碼
我想讓如果連接的USB設備中的一個具有關鍵的代碼返回true,
List<DriveInfo> list = new List<DriveInfo>(DriveInfo.GetDrives());
foreach (DriveInfo drive in list)
{
if (drive.DriveType == DriveType.Removable)
{
if ((File.Exists(drive.RootDirectory + "Key.txt")) &&
File.Exists(drive.RootDirectory + "SerialNumber.txt"))
{
string KeyFromUsb = (System.IO.File.ReadAllText(drive.RootDirectory + "Key.txt"));
string serialusb = (System.IO.File.ReadAllText(drive.RootDirectory + "SerialNumber.txt"));
int serialNumbeFromUsb = Convert.ToInt32(serialusb);
string KeyFromDataBase = FoundKey(serialNumbeFromUsb);
if (KeyFromDataBase == KeyFromUsb)
{
ok = true;
}
else
{
return false;
}
}
}
}
只要您的條件不滿意,代碼總是返回false,但您沒有返回true。也許修改'ok = true;'這行到'return true;'可以幫助嗎? –
foreach循環退出一次在else語句中返回false。因此你是否連接了超過1個USB設備的問題。考慮設置一個「標誌」,並將你的if語句移到foreach循環外的「flag」 –