我有一个包含3100个子网(192.168.1.0/24)的导入Excel工作表作为示例。我希望能够使用存储的变量搜索前3个八位字节。如果我能做到这一点,我可以编辑电子表格,只包含前3个八位字节,并在程序的未来获得我想要的结果。非常感谢你提前。
string octets = ("10.2.30");
var match = false;
for (int i = 0; i < xlRange.Rows.Count; i++)
{
IPAddress excelIP;
if (IPAddress.TryParse(xlWorksheet.Cells[i + 1, 1].Value.ToString(), out excelIP))
{
if (excelIP.ToString().Equals(octets))
{
match = true;
Console.Write(excelIP.ToString());
Console.WriteLine(" -This id was found");
}
}
}
if (!match)
{
Console.WriteLine("No Match ");
}
xlWorkbook.Close(); xlApp = null;
}
答案 0 :(得分:0)
以下是一些方法:
octets
字符串,并将其与excelIP
字符串的开头相匹配。octets
字符串拆分为List
,并将该列表中的元素与分配为八位字节列表时excelIP
的相同元素数进行比较。在任何一种情况下,您都需要添加对System.Linq
的引用才能使用表达式。
using System;
using System.Linq;
using System.Net;
对于#1:
// add a trailing '.' so we can match the start of the excelIP
string octets = ("10.2.30.");
var match = false;
for (int i = 0; i < xlRange.Rows.Count; i++)
{
// Get the IP address portion of the CIDR string
var cellString = xlWorksheet.Cells[i + 1, 1].Value.Split('/')[0];
IPAddress excelIP;
// If cellString starts with the octets string and it's a valid IP address...
if (cellString.StartsWith(octets) && IPAddress.TryParse(cellString, out excelIP))
{
match = true;
Console.Write(excelIP.ToString());
Console.WriteLine(" -This id was found");
}
}
对于#2:
var match = false;
string octets = ("10.2.30");
string[] octetsToMatch = octets.Split('.');
for (int i = 0; i < xlRange.Rows.Count; i++)
{
// Get the IP address portion of the CIDR string
var cellString = xlWorksheet.Cells[i + 1, 1].Value.Split('/')[0];
IPAddress excelIP;
if (IPAddress.TryParse(cellString, out excelIP))
{
// Compare the first octets of the IP address with our octetsToMatch
if (octetsToMatch.SequenceEqual(cellString.Split('.').Take(octetsToMatch.Length)))
{
match = true;
Console.Write(excelIP.ToString());
Console.WriteLine(" -This id was found");
}
}
}