c# Get array index id - c#

Not sure if am on the right track but I want to find a index id of an array and check if it's equal to another id then display a message. it not working for some reason.
int _findID = 1;
using (StreamReader reader = new StreamReader("textfile.txt"))
{
string line = reader.ReadLine();
while (line != null)
{
string[] array = {line};
for (int i = 0; i < array.Length; i++)
{
if (array[i] == findID)
{
MesssageBox.show("Line found!!")
}
}
}
}
Any help appreciated

try
if(int.Parse(array[i]) == findID)
instead of
if (array[i] == findID)
You have to convert your string representation of your number to a int and then compare both int's.
this is even shorter than iterating over an array which always has 1 element:
while (line != null) {
if(int.Parse(array[i]) == findID)
MesssageBox.Show("Line found!!")
}
EDIT
Try
int _findID = 1;
List<String> names = new List<string>()
using (StreamReader reader = new StreamReader("textfile.txt"))
{
string line = reader.ReadLine();
int lineCount = 0;
while (line != null)
{
lineCount++;
names.Add(line);
if (lineCount == _findID)
MessageBox.Show("Line found!!");
}
}

#user1285872: array.Length this will give array length 1 in your case when you check if (array[i] == findID) thi will be (0==findID) if the value of findID ==0 then message will show.

Your code has various problems:
First if the file is not empty you have an endless loop as you read the line once and always check the same line:
string line = reader.ReadLine();
while (line != null) {}
The array is always 1 item long as you create it in the loop itself.
But for the problem with the lineID, what exactly is the content of such a line?

Related

How to skip multiple iterations in a while loop

I'm reading a text file line by line in a While loop. When I reach a specific line I want to skip the the current and the next 3 iterations.
I guess I can do it using a counter and things like that. But I was wondering if there is a more elegant way?
using (var sr = new StreamReader(source))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (line == "Section 1-1")
{
// skip the next 3 iterations (lines)
}
}
}
Have a for loop to execute sr.ReadLine 3 times and discard the result like:
using (var sr = new StreamReader(source))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (line == "Section 1-1")
{
for (int i = 0; i < 3; i++)
{
sr.ReadLine();
}
}
}
}
You should check for sr.ReadLine returning null or if the stream has come to an end.
You can use File.ReadAllLines with method extesions:
public static IEnumerable<string> SkipLines(string file, string line, int count)
{
var enumerable = File.ReadLines(file).GetEnumerator();
while (enumerable.MoveNext())
{
var currentLine = enumerable.Current;
if (currentLine == line)
{
var currentCount = 0;
while(enumerable.MoveNext() && currentCount < count)
{
currentCount += 1;
}
}
yield return currentLine;
}
}
usage:
foreach (var line in SkipLines(source, "Section 1-1", 3))
{
// your line
}
Keep in mind: ReadLines is lazy - not all lines are loaded into memory at once.
Make yourself a function that discards a given number of lines (DiscardLines) and use it:
string line;
while ((line = sr.ReadLine()) != null)
{
if (line == "Section 1-1")
{
DiscardLines(sr, 3);
}
}
That keeps the main loop very simple. The counter is now hidden in DiscardLines.
using (var sr = new StreamReader(source))
{
string line;
int linesToSkip = 0;
while ((line = sr.ReadLine()) != null)
{
if (linesToSkip > 0)
{
linesToSkip -= 1;
continue;
}
if (line == "Section 1-1")
{
// skip the next 3 iterations (lines)
linesToSkip = 3;
}
}
}

Counting the number of words from a file

A word in this context is defined is a letter or a number. However, something like \n is not considered a word.
Below in my code I am trying to count the number of words in a file but at the for loop's local variable declaration I get the error Null Reference exception.
I am not sure why I get this error. I get the variable Line equal to null which shouldn't happen because the text file DOES have one word "hello world" in it..
StreamReader sr = new StreamReader(filePath);
while (sr.ReadLine()!=null)
{
Line =sr.ReadLine();
for (**int i = 1**; i < (Line.Length+1); i++)
{
if (Char.IsLetterOrDigit(Line[i]) == true && Char.IsLetterOrDigit(Line[i - 1]) == true)
{
if (LetterRecent == false)
{
wordCount = wordCount + 1;
}
LetterRecent = true;
}
else
{
LetterRecent = false;
}
}
}
sr.Close();
You're doing ReadLine() twice for each line.
You could do something like:
count = 0;
while (line = sr.ReadLine()) {
char oldChar = 0;
for (char c in line) {
if (c != oldChar && Char.IsLetterOrDigit(c)) count++;
oldChar = c;
}
}
You are discarding half of the lines in the file by calling sr.ReadLine() twice. If you read the last line of the file in the while statement, the call to Line.Length will throw the null reference exception.
Try something this:
var wordCount = 0;
var line = sr.ReadLine();
while( line != null ) {
for( var i = 1; i < line.Length; i++ ) {
// Count words
}
line = sr.ReadLine();
}
You need to declare wordCount before using it.
Int wordCount = 0;
while (sr.ReadLine()!=null)
{
Update your loop condition to be like this:
while (sr.Peek() >= 0)
{
Line = sr.ReadLine();
}

c# search string in txt file

I want to find a string in a txt file if string compares, it should go on reading lines till another string which I'm using as parameter.
Example:
CustomerEN //search for this string
...
some text which has details about the customer
id "123456"
username "rootuser"
...
CustomerCh //get text till this string
I need the details to work with them otherwise.
I'm using linq to search for "CustomerEN" like this:
File.ReadLines(pathToTextFile).Any(line => line.Contains("CustomerEN"))
But now I'm stuck with reading lines (data) till "CustomerCh" to extract details.
If your pair of lines will only appear once in your file, you could use
File.ReadLines(pathToTextFile)
.SkipWhile(line => !line.Contains("CustomerEN"))
.Skip(1) // optional
.TakeWhile(line => !line.Contains("CustomerCh"));
If you could have multiple occurrences in one file, you're probably better off using a regular foreach loop - reading lines, keeping track of whether you're currently inside or outside a customer etc:
List<List<string>> groups = new List<List<string>>();
List<string> current = null;
foreach (var line in File.ReadAllLines(pathToFile))
{
if (line.Contains("CustomerEN") && current == null)
current = new List<string>();
else if (line.Contains("CustomerCh") && current != null)
{
groups.Add(current);
current = null;
}
if (current != null)
current.Add(line);
}
You have to use while since foreach does not know about index. Below is an example code.
int counter = 0;
string line;
Console.Write("Input your search text: ");
var text = Console.ReadLine();
System.IO.StreamReader file =
new System.IO.StreamReader("SampleInput1.txt");
while ((line = file.ReadLine()) != null)
{
if (line.Contains(text))
{
break;
}
counter++;
}
Console.WriteLine("Line number: {0}", counter);
file.Close();
Console.ReadLine();
With LINQ, you could use the SkipWhile / TakeWhile methods, like this:
var importantLines =
File.ReadLines(pathToTextFile)
.SkipWhile(line => !line.Contains("CustomerEN"))
.TakeWhile(line => !line.Contains("CustomerCh"));
If you whant only one first string, you can use simple for-loop.
var lines = File.ReadAllLines(pathToTextFile);
var firstFound = false;
for(int index = 0; index < lines.Count; index++)
{
if(!firstFound && lines[index].Contains("CustomerEN"))
{
firstFound = true;
}
if(firstFound && lines[index].Contains("CustomerCh"))
{
//do, what you want, and exit the loop
// return lines[index];
}
}
I worked a little bit the method that Rawling posted here to find more than one line in the same file until the end. This is what worked for me:
foreach (var line in File.ReadLines(pathToFile))
{
if (line.Contains("CustomerEN") && current == null)
{
current = new List<string>();
current.Add(line);
}
else if (line.Contains("CustomerEN") && current != null)
{
current.Add(line);
}
}
string s = String.Join(",", current);
MessageBox.Show(s);

How to skip to next item if current variable is null

I have a function that retrieves a list of device names and stores then in a variable. Then the next step is to get info using 1 device name per line and keep going till the loop is complete.
String text = "";
String errors = "";
for (int i = 0; i < collection.Result.Count; i++)
{
deviceNames += collection.Result[i].DeviceName + Environment.NewLine;
getvirtuals.Location = deviceNames;
var virtuals = client.GetKnownVirtuals(getvirtuals, LtmKeyType.VirtualAddressPort);
if (virtuals.Result == null)
{
i++;
getvirtuals.Location = deviceNames;
for (int v = 0; v < virtuals.Result.Count; v++)
{
try
{
LtmKey virtualKey = new LtmKey();
virtualKey.Location = virtuals.Result[v].Location;
virtualKey.LocationType = virtuals.Result[v].LocationType;
virtualKey.Key = virtuals.Result[v].Key;
virtualKey.KeyType = LtmKeyType.VirtualAddressPort;
virtualKey.AdminGroup = admingroupComboBox.Text;
var memberStatus = client.GetMemberStatus(virtualKey);
for (int j = 0; j < memberStatus.Result.Count; j++)
{
VirtualMemberStatus status = memberStatus.Result[j];
text += String.Format("{5},{4},{0},{1},{2},{3}" + Environment.NewLine, status.Member.Address, status.Member.Port, status.EffectiveStatus, status.DesiredStatus, virtualKey.Key.Replace(":", ","), DateTime.UtcNow);
toolStripProgressBar1.PerformStep();
}
}
catch
{
errors += String.Format("{0} Error Code: 2, Error occurred, check device name (case senstive) and admin group. This error may also occur due to connection loss, try again." + Environment.NewLine, DateTime.UtcNow);
}
}
this.allResultsBox.Text = text;
getallstatusButton.Enabled = true;
}
}
The problem that I am running into is that if virtuals is null the tool crashes, instead what I want to do is if virtuals = null I want to move onto the next item from the list. I have tried a if statement but it is not working the way planned, it still comes back as null.
Well this seems like a problem to start with:
if (virtuals.Result == null)
{
i++;
getvirtuals.Location = deviceNames;
for (int v = 0; v < virtuals.Result.Count; v++)
...
If virtuals.Result is null, how do you expect virtuals.Result.Count to work? I suspect you meant:
if (virtuals.Result != null)
However, I suspect you really just want:
// Keep going with the next iteration of the for loop
if (virtuals == null || virtuals.Results == null)
{
continue;
}
If all you want is to go to the next loop iteration if virtuals is null then you want
if (virtuals == null) continue;
How about just inserting:
if(virtuals == null)
continue;
right after the line
var virtuals = client.GetKnownVirtuals(getvirtuals, LtmKeyType.VirtualAddressPort);
Have you tried changing the line:
if (virtuals.Result == null)
to:
if ((virtuals != null) && (virtuals.Result != null))
If this doesn't solve your issue, then you need to indicate what the additional errors are.
if (virtuals.Result == null)
make this
if (virtuals == null)

use unassigned local variable 'multidimension'

I am getting an error use unassigned local variable 'multidimension' from below code. I am trying to put the data returned back from the text file in a multidimensional array by splitting them and put each row in in the array
private void button1_Click_1(object sender, EventArgs e)
{
string[,] Lines;
//string[][] StringArray = null;
//to get the browsed file and get sure it is not curropted
try
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
using (StreamReader sr = new StreamReader(openFileDialog1.FileName))
{
string[] data= null;
string ReadFromReadLine;
while ((ReadFromReadLine = sr.ReadLine()) != null)
{
data = ReadFromReadLine.Split(',');
for (int i = 0; i <= ReadFromReadLine.Length; i++)
{
for (int j = 0; j <= data.Length; j++ )
{
string[,] multidimensional;
multidimensional[i, j] = data[j];
}
}
}
//foreach(string s in Lines)
//{
// EditItemComboBox.Items.Add(s);
//}
}
FilePath.Text = openFileDialog1.FileName;
//textBox1.Text += (string)File.ReadAllText(FilePath.Text);
}
}
catch(IOException ex)
{
MessageBox.Show("there is an error" + ex+ "in the file please try again");
}
}
Any Ideas what I am doing wrong?
string[,] multidimensional;
should be:
string[,] multidimensional = new string[ReadFromReadLine.Length, data.Length];
and moved out of the for loops and maybe sent to a method, cached, or something
You are just defining an array called 'multidimensional', but not assigning it to anything.
for (int j = 0; j <= data.Length; j++ )
{
string[,] multidimensional = new String[i,data.Length]
multidimensional[i, j] = data[j];
}
However, I am not sure I am following what you are trying to do in the innermost loop. You are defining a new array called 'multidimensional' each time you are looping through the elements in data and the old data is lost each time.
If 'multidimensional' is suppose to contain the contents of the entire file, you need to define it outside of the first loop, but to use an array like you are, you need to know the number of lines in your file. If you are using C#2 or greater, a List<> would be a better choice
var list = new List<String[]>();
while ((ReadFromReadLine = sr.ReadLine()) != null)
{
data = ReadFromReadLine.Split(',');
list.Add(data);
}

Categories

Resources