Unable to locate a number found in a text file c# - c#

I have an application which an ST-LINK programs firmware too and then a report is made on the buffer size, data bits etc.
I have a text file which stores these results. However, there may be a lot of circuit boards in one batch and each time they need to increase there product number by one. So what I want to do is get the program to look at the last board report, see if it has the same batch number (as batches will all be done at once), and if it does increase the product number by 1. If it doesn't have the same batch number then it must be a new batch and the product number will be 1.
At the moment the product number is not updating. Every time it is returning 1.
Here is my code:
public int previousNumber()
{
int pNumber = 0;
string line; //set string
int counter = 0; //create int
int numberOfLines = File.ReadLines("report.txt").Count();
System.IO.StreamReader file = new System.IO.StreamReader("report.txt"); //create streamreader
while ((line = file.ReadLine()) != null) //until no empty lines
{
string[] allLines = File.ReadAllLines("report.txt"); //read in report file
if (allLines[numberOfLines - 9] == batchNumberTextBox.Text)
{
pNumber = int.Parse(allLines[numberOfLines - 7]);
}
else
{
pNumber = 0;
}
}
file.Close();
pNumber = pNumber + 1;
return pNumber;
}
private void saveReport()
{
getValues();
int number = previousNumber();
BatchNumber = batchNumberTextBox.Text;
SerialNumber = serialNumberTextBox.Text;
ProductNumber = number;
string ProductNumberString = ProductNumber.ToString();
string inDate = DateTime.Now.ToString("f",
CultureInfo.CreateSpecificCulture("en-UK")); //set date in that format
try
{
board newBoard = new board(BatchNumber, SerialNumber, ProductNumberString, BufferSize, StopBits, Parity, DataBits, baudRate, inDate);
newBoard.Save("report.txt");
File.AppendAllText("batches.txt", "BATCH NUMBER: " + BatchNumber + " - DATE: " + inDate + Environment.NewLine);
System.Windows.MessageBox.Show("Report Saved");
}
catch
{
System.Windows.MessageBox.Show("Save failed"); //tell user save failed
}
}
And here is the text file for the reports:
Can you see anywhere why it may not be working? I feel like I may have gone a weird way about this so if you can think of a better way it would be much appreciated!
Thank you in advance,
Lucy

I take it, the batch number is 1234 in your data sample. If so, it's offset from the last line is -10 and not -9. This is the primary source of your error.
There is also a lot of redundancy in your code: you read the whole file several times while reading it once and storing all its lines in an array would be pretty enough.
A simplified (but still correct) version of previousNumber() may look like this:
public int previousNumber()
{
var allLines = File.ReadAllLines("report.txt");
int pNumber = 0;
if (allLines.Length > 10 && allLines[allLines.Length - 10] == batchNumberTextBox.Text)
// Note: if the desired value is "1" and not "4096", then the offset is "-8".
int.TryParse(allLines[allLines.Length - 8], out pNumber);
return pNumber + 1;
}

Related

convert number index of string array to double array

I am reading from a text file, pulling each line, looking for the first line with 1|, and then converting it into an array. For this I only want the 4th index so that I can sum and count the array.
Here is what is converts from the text file into an array
1|123456|01/06/2019|123456|100.00|USD|DUE UPON RECEIPT|TEST1||98790125|TEST2|TEST3|N
so [0] = 1, [2] = 123456, etc. etc. I am trying to pull 100.00 from it and put it in it's own array, so that I can easily double sum, and count the elements. It's proving difficult for me since the original array is a string though.
I've tried creating a separate string array already split, and then pulling the 4th index and creating an double array that I can count and sum. I've also tried just splitting and creating an int array in one line from the str it pulls.
string str;
using (StreamReader file = new StreamReader("c:\\testdoc.txt"))
while ((str = file.ReadLine()) != null)
{
string[] strArray = str.Split('|');
if (strArray[0] == "1")
{
double[] itotals = strArray.Select(i => Convert.ToDouble(i)).ToArray();
int count = itotals.Length;
double amt = itotals.Sum();
Console.WriteLine("Count: " + count + " Amt: " + amt);
}
else
{
}
}
I expect it to find the line starting with 1|, then tell console to write count: 1 amt: 100.00, but I actually just get errors that input strings were not in the correct format. I know that I need to pull the 4th index after I split, but I'm not sure where to do that.
Try this
string str;
int count = 0;
double amt = 0;
using (StreamReader file = new StreamReader("c:\\testdoc.txt"))
while ((str = file.ReadLine()) != null)
{
string[] strArray = str.Split('|');
if (strArray[0] == "1")
{
string itotals = strArray[4];
count = count+1;
amt = amt + Convert.ToDouble(strArray[4]);
Console.WriteLine("Count: " + count + " Amt: " + amt);
}
else
{
}
}

Reading .PAK files with c#

I want my app capable of detecting when a certain string is contained in one line, after that, it will return the line number and subtract 8. Then it will search line by line (again) until it reached the line obtained before, read it, and show it on a messagebox*(the whole line)*.
It always detects the line with the asked string and subtracts 8 to it. The problem, is that returns an empty string every time! I'v tried many different things, and always comes an empty string. In some lines it returns chars like ";" or "<".
However, all this, must be done to a .PAK file. The file has +- 4Gb of size, The speed is not relevant in the case.
Preview of te first lines of the PAK file: https://imgur.com/1GFBPlN
Preview of the code:
int counter = 0;
string line;
int linhaM = 8;
int Possivel = 0;
bool FindCID = false;
string str = "";
System.IO.StreamReader file =
new System.IO.StreamReader("C:/Program Files/mypersonalpath/pakchunk0-WindowsClient.pak");
while ((line = file.ReadLine()) != null)
{
if (line.Contains("Stringxyz"))
{
MessageBox.Show(counter.ToString());
break;
}
counter++;
}
linhaM = counter;
Possivel = counter -8;
MessageBox.Show(Possivel.ToString());
counter = 0;
while (((line = file.ReadLine()) != null) && FindCID == false)
{
if (counter == Possivel)
{
MessageBox.Show("The line 8 lines above the line that contains stringxyz is: " + line);
break;
}
counter++ ;
}
file.Close();
textBox1.Text = str;
}
Am I treating PAK files in a wrong way? What am I doing wrong? Is what i'm asking for possible? Thanks
(This is my first time asking a question here, sorry if I did anything wrong)

reading a text file and multiplying the first line by each of the other lines

i'm working on this homework and i need to read a text file of integers, store the numbers into arrays. Then square the numbers in each line (after 25) and then divide the square by 25 and then check if the result is bugger than 150
Where i'm stuck is reading the numbers of each line and using them in my method like i'm supposed to, so far my loop and arrays prints put each number in the file in order.
i'd really appreciate any help with the array part, Thanks.
Here is the text file:
25 150
60
63
61
70
72
68
66
68
70
so, take Math.Pow(60,2) / 25, and Math.Pow(63,2) / 25 and so on. then if it is higher than 150, print "yes" and print "no" if it is lower than 150
here is what i have:
i have another class
class Resistors
{
//declare variables for the resistance and the volts.
private int resistance;
private int volts;
public Resistors(int p1, int p2)
{
resistance = p2;
volts = p1;
}
//GetPower method.
//purpose: to get calculate the power dissipation of the resistor.
//parameters: it takes two intigers.
//returns: the total power as a double.
public double GetPower()
{
return (Math.Pow(volts, 2) / resistance);
}
}
and here is the rest.
static void Main(string[] args)
//declare some variables and an array.
const int MAX = 50;
string inputLine = "";
Resistors[] resistor = new Resistors[MAX];
//declare a counter and set to zero
int count = 0;
// This line of code gets the path to the My Documents Folder
string environment = System.Environment.GetFolderPath
(System.Environment.SpecialFolder.Personal) + "\\";
WriteLine("Resistor Batch Test Analysis Program");
WriteLine("Data file must be in your Documents folder");
Write("Please enter the file name: ");
string input = Console.ReadLine();
// concatenate the path to the file name
string path = environment + input;
// now we can use the full path to get the document
StreamReader myFile = new StreamReader(path);
while (inputLine != null)
{
inputLine = myFile.ReadLine();
if (inputLine != null && count < MAX)
{
string[] data = inputLine.Split();
int dataR = int.Parse(data[0]);
string[] pie = inputLine.Split();
int pieV = int.Parse(pie[0]);
resistor[count++] = new Resistors(dataR, pieV);
}
}
WriteLine("Res#\tDissipitation\tPassed");
for (int j = 0; j < count; j++)
{
WriteLine("{0:d}\t{1:N}", j + 1, resistor[j].GetPower());
}
ReadKey();
}
I think this should do what you need :
Edit:
Based on your comments, if you want to read multiple values on the first line, you can separate them by a comma, and then split on.
25,150
60
63
61
70
72
68
66
68
70
static void Main(string[] args)
{
// This line of code gets the path to the My Documents Folder
string environment = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "\\";
Console.WriteLine("Resistor Batch Test Analysis Program");
Console.WriteLine("Data file must be in your Documents folder");
Console.Write("Please enter the file name: ");
string input = Console.ReadLine();
// concatenate the path to the file name
string path = environment + input;
// Will read all lines
var lines = File.ReadAllLines(path).ToList();
// Will get the first line arguments and split them on the comma, you add more arguments if need, just separate them by a comma
var firstLineArgs = lines[0].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(t => Convert.ToInt32(t))
.ToArray();
// Will skip the first line arguments and parse all the following numbers
var numbers = lines.Skip(1)
.Select(t => Convert.ToInt32(t))
.ToList();
// Will create each Resistors object with the first line arguments (25) and the actual number
// You can do whatever you want with the second arguments (150)
var resistors = numbers.Select(t => new Resistors(firstLineArgs[0], t))
.ToList();
Console.WriteLine("Res#\tDissipitation\tPassed");
foreach (var item in resistors)
{
// Check if item.GetPower() is greather firstLineArgs[1] (150)
// I don't know what you want to do if it's greater
Console.WriteLine("{0:d}\t{1:N}", resistors.IndexOf(item) + 1, item.GetPower());
}
Console.ReadKey();
}
You will find that the code you have written calls your Resistors constructor with the 1st and 2nd line of your input file, then with the 3rd and 4th lines, then with the 5th and 6th lines ...
Your description suggests that you want to retain the first line then use it in construction of each Resistor object. Perhaps I have misunderstood your problem. You might want to consider showing a few points of output against a few points of expected output.
Also your 'inputLine.Split()' is unnecessary. you can just parse the inputLine string.
Let me took few lines from you code:
if (inputLine != null && count < MAX)
{
string[] data = inputLine.Split();
int dataR = int.Parse(data[0]);
string[] pie = inputLine.Split();
int pieV = int.Parse(pie[0]);
}
You are actually doing the same this with split(); and also Split() is not necessary there, you can achieve the same with int dataR = int.Parse(inputLine); and int pieV = int.Parse(inputLine);
From the example you mentioned in the question
take Math.Pow(60,2) / 25, and Math.Pow(63,2) / 25 and so on.
You have to assign the first value in the file as resistance if so( and i understand correctly) you can do the whole by using the following code:
List<string> stringArray = File.ReadAllLines(#"filePath").ToList();
List<int> intList= stringArray.Select(x => x!=null || x!="" ?0:int.Parse(x)).ToList();
//Now `intList` will be the list of integers, you can process with them;
int resistance=intArray[0];
for (int i = 1; i < intArray.Count ; i++)
{
resistor[i] = new Resistors(intArray[i], resistance);
}
You can try with your code too :
StreamReader myFile = new StreamReader(#"path_here");
const int MAX = 50;
string inputLine = "";
// Resistors[] resistor = new Resistors[MAX];
int count = 0;
int resistance = 0;
while (inputLine != null)
{
inputLine = myFile.ReadLine();
if (inputLine != null && count < MAX)
{
int inputInteger = int.Parse(inputLine);
if (count == 0) { resistance = inputInteger; }
resistor[count++] = new Resistors(inputInteger, resistance);
}
}

Formating a File to a listBox 5 lines at a time

stuck on a last minute assignment and could really really use a hand.
i have a file that hold dna codons, 1 per line in a set of 3 EXAMPLE:
acg
att
atg
acc
etc...
i need to output these into a list box 5 at a time in the format:
Line 01: acg att atg acc agg
line 02: act tga tcg....etc
for all 1000 codons.
private void btnOpen_Click(object sender, EventArgs e)
{
reader = new StreamReader("DNA.txt");
int counter = 0;
do{
counter++;
s = reader.ReadLine();
lstOut.Items.Add("Line " + counter.ToString("00") + ": " + s);
}
while (!reader.EndOfStream);
reader.DiscardBufferedData();
reader.BaseStream.Position = 0;
}
this is currently all i have wrtten and as i am fairly new to c# i am not sure how to get these files to read out 5 at a time. the best i have got is the 15 charactars together but in this format
acgtcgaccagtcga
without the spaces
i tried a ReadBlock and had it set up to read every 25 charactars (not sure why it was taking 25 to come out with the 15 letter) but it kept crashing the 2nd time through the loop. due at 10:00 tonight if anyone has any ideas i would be so thankful!!
Have you tried something like this? :
var lines = File.ReadAllLines("DNA.txt");
for(int i=0;i<lines.Count();i+=5)
{
lstOut.Items.Add(string.Format("Line {0}:{1}",
(i/5).ToString("00"),
string.Join(" ",lines.Skip(i).Take(5))));
}
How about this aproach
int max ;
int i ;
int numLine ;
int set ;
string line ;
var lines = File.ReadAllLines("DNA.txt");
max = lines.Count() ;
i = 0 ;
numLine = 1 ;
while(i < max)
{
line = string.Format("Line {0}:",numLine.toString("00")) ;
//logic to handle case where your file does not have multiple of 5 number of lines
for(set = 1; (i < max) && (set <= 5); set++)
{
line += lines[i] + " ";
i++ ;
}
lstOut.Items.Add(line) ;
numLine++ ;
}

How to edit and replace a group of lines of a text file using c#?

I have a large text file(20MB), and I'm trying to change every 4th & 5th line to 0,0
I've tried with the following code but I will be interested to know if theres any better way of doing it..
EDIT:
Power = new List<float>();
Time = new List<float>();
string line;
float _i =0.0f;
float _q =0.0f;
int counter = 0;
StreamReader file = new StreamReader(iqFile2Open);
while ((line = file.ReadLine()) != null)
{
if (Regex.Matches(line, #"[a-zA-Z]").Count == 0)
{
string[] IQ = line.Split(',');
if (IQ.Length == 2)
{
_i = float.Parse(IQ[0]);
_q = float.Parse(IQ[1]);
double _p = 10 * (Math.Log10((_i * _i) + (_q * _q)));
if((counter%4)==0 || (counter%5)==0)
sw.WriteLine("0,0");
else
sw.WriteLine(string.Format("{0},{1}", _i, _q));
counter++;
}
}
}
Thanks in advance.!
You can read in all of the lines, map each line to what it should be based on it's position, and then write them all out:
var lines = File.ReadLines(inputFile)
.Select((line, i) => ComputeLine(line, i + 1));
File.WriteAllLines(outputFile, lines);
As for the actual mapping, you can mod the line number by 5 to get an "every 5th item" result, and then just compare the result to the two mod values you care about. Note that since you don't want the first item wiped out it's important that the index is 1-indexed, not zero indexed.
private static string ComputeLine(string line, int i)
{
if (i % 5 == 4 || i % 5 == 0)
return "0,0";
else
return line;
}
This streams through each line in the file, rather than loading the entire file into memory. Because of this it's important that the input and output files be different. You can copy the output file to the input file if needed, or you could instead use ReadAllLines to bring the entire file into memory (assuming the file stays suitably small) thus allowing you to write to the same file you read from.
What exactly are you trying to replace? Are you replacing by specific LINE or specific TEXT?
If you are looking to replace specific text you can easily do a string.Replace() method...
StreamReader fileIn = new StreamReader("somefile");
string fileText = fileIn.Readlines();
fileText = fileText.Replace("old", "new");
//Repeat last line for all old strings.
//write file...

Categories

Resources