I am reading some ip addresses from a txt file. I want to break them in a set of 30 IP address and assign them to their seperate variables for further reference. The issue is, this text file will contain more ip address in coming days and want my application(console application) to be scalable. I am newbie to .net so i am sorry if i am asking something very basic but pls guide me. I want to achieve something logically like below
Okay, so the below should accomplish this, and I know there are other ways to accomplish this as well, but this should get you started
var ipAddresses = new List<List<string>>();
using (StreamReader sr = new StreamReader("C:\\\\ipaddresses.txt"))
{
string ipAddress;
int ipAddressLocation;
int ipAddressCount = 1;
// Read to the end of the file
while(!sr.EndOfStream)
{
// Read the ip address
ipAddress = sr.ReadLine();
// Determine which array the ip address should be part of
ipAddressLocation = (int)Math.Floor(ipAddressCount/30.0);
// Check that the array exists, otherwise, create it
if (ipAddresses.Count <= ipAddressLocation)
{
ipAddresses.Add(new List<string>());
}
// Add the ip address to its' array
ipAddresses[ipAddressLocation].Add(ipAddress);
ipAddressCount++;
}
}
Please dont mind, i am trying to understand your logic, and so far its amazing. I am having just one problem, if there are any ip addresses that do not fit in the 30 set, they are not counted. I mean i have total 126 ip addresses. As you can see, till 120 it forms 4 sets and the rest 6 ip addresses are not included. Can you kindly help me out
thanks alot in advance and i wont bother you with continous request. this is the last one sir
I changed ipAddressCount = 1 to ipAddressCount = 0
var ipAddresses = new List<List<string>>();
using (StreamReader sr = new StreamReader("C:\\\\ipaddresses.txt"))
{
string ipAddress;
int ipAddressLocation;
int ipAddressCount = 1;
// Read to the end of the file
while(!sr.EndOfStream)
{
// Read the ip address
ipAddress = sr.ReadLine();
// Determine which array the ip address should be part of
ipAddressLocation = (int)Math.Floor(ipAddressCount/30.0);
// Check that the array exists, otherwise, create it
if (ipAddresses.Count <= ipAddressLocation)
{
ipAddresses.Add(new List<string>());
}
// Add the ip address to its' array
ipAddresses[ipAddressLocation].Add(ipAddress);
ipAddressCount++;
}
}
This gave me 5 arrays, the first 4 have 30 ip addresses each, the last has 6 (verified using a debugger).