如果连接了多个USB设备(至少一个包含密钥),则代码返回false。
如果其中一个连接的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;
}
}
}
}
答案 0 :(得分:1)
很常见的逻辑问题。
将ok = true
更改为return true
并将return false
移至循环外部。
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)
{
return true;
}
}
}
}
return false;
答案 1 :(得分:0)
List<DriveInfo> list = new List<DriveInfo>(DriveInfo.GetDrives());
//var i = 0;
int i = 0;
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)
{
i = 1; //or simply return true, this will exit the loop
}
}
}
}
if(i == 1)
{
ok = true;
}
或简单地返回true。 (不要在foreach循环中返回false)。
答案 2 :(得分:0)
List<DriveInfo> list = new List<DriveInfo>(DriveInfo.GetDrives());
var condSatisfied = false;
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;
condSatisfied = true;
}
}
}
}
return condSatisfied