[英]c# code issue in .net application
如果连接了多个 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;
}
}
}
}
很常见的逻辑问题。
更改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;
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)。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.