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)
Related
I was just learning and had a problem working with files.
I have a method that has two inputs, one at the beginning of the line (lineStart) I want and the other at the end of the line (lineEnd)
I need method that extract between these two numbers for me and write on file .
ex ) lineStart = 20 , lineEnd = 90, in output Must be = 21-89 line of txt file.
string[] lines = File.ReadAllLines(#"");
int lineStart = 0;
foreach (string line0 in lines)
{
lineStart++;
if (line0.IndexOf("target1") > -1)
{
Console.Write(lineStart + "\n");
}
}
int lineEnd = 0;
foreach (string line1 in lines)
{
lineEnd++;
if (line1.IndexOf("target2") > -1)
{
Console.Write(lineEnd);
}
}
// method grabText(lineStart,lineEnd){}
enter code here
It is just a line of code
string[] lines = File.ReadLines(#"").Skip(lineStart).Take(lineEnd-lineStart);
Notice also that I use ReadLines and not ReadAllLines. The first one doesn't load everything in memory.
It is not very clear what are the boundary of the lines to take but of course it is very easy to adapt the calculation
If your text file is huge, don't read it into memory. Don't look for indexes either, just process it line by line:
bool writing = false;
using var sw = File.CreateText(#"C:\some\path\to.txt");
foreach(var line in File.ReadLines(...)){ //don't use ReadAllInes, use ReadLines - it's incremental and burns little memory
if(!writing && line.Contains("target1")){
writing = true; //start writing
continue; //don't write this line
}
if(writing){
if(line.Contains("target2"))
break; //exit loop without writing this line
sw.WriteLine(line);
}
}
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...
I'm trying to read x and y values from a text file into a string array where the line is being split on the ','
However, when I run this code I get an error saying the index was out of the bounds of the array on the first element. I've tried using temporary strings to store the data and then convert them but I still get the same error on the second element. here is my code I have implemented without the temporary strings.
string line;
while ((line = coordStream.ReadLine()) != null)
{
string[] temp = new string[2];
temp[0] = "";
temp[1] = "";
temp = line.Split(',');
trees[count].X = Convert.ToInt16(temp[0]);
trees[count].Y = Convert.ToInt16(temp[1]);
count++;
}
Here is the code with the temporary storage too:
string line;
while ((line = coordStream.ReadLine()) != null)
{
string[] temp = new string[2];
temp[0] = "";
temp[1] = "";
temp = line.Split(',');
string xCoord = temp[0];
string yCoord = temp[1];
trees[count].X = Convert.ToInt16(xCoord);
trees[count].Y = Convert.ToInt16(yCoord);
count++;
}
I know this seems a trivial error but I cannot seem to get this working. If I debug and step through the array manually it works but when I don't step through it(i.e let the program run) these errors are thrown
EDIT: The first 10 lines of data are as follows:
654,603
640,583
587,672
627,677
613,711
612,717
584,715
573,662
568,662
564,687
There are no empty lines in the text file.
As pointed out by Jon Skeet, removing the temp assignments seems to have fixed this error. However even with the assignments it should still have worked. The following code sample inside the while loop works:
string[] temp;
temp = line.Split(',');
trees[count].X = Convert.ToInt16(temp[0]);
trees[count].Y = Convert.ToInt16(temp[1]);
count++;
The number of trees is known but I'd like to thank everyone for their input. Expect more questions in the near future :D
Try using a List<Point> for your trees collection instead of an array. This will help if you don't know the correct count upfront.
var trees = new List<Point>();
while (...)
{
...
trees.Add(new Point(x, y));
}
The second possible issue is when the input line does not contain valid data (for example, is empty). Often the last line with data ends with a newline thus the last line is empty.
while ((line = coordStream.ReadLine()) != null)
{
var temp = line.Split(',');
if (temp.Length != 2)
continue;
....
}
var lineContents = File.ReadAllLines("").Select(line => line.Split(',')).Where(x => x.Count() == 2);
var allTrees = lineContents.Select(x => new Trees() { X = Convert.ToInt16(x[0]), Y = Convert.ToInt16(x[1]) });
I have a problem with my C# program: I have created a quiz with 10 questions and 10 images.
I get this Length cannot be less than zero.\r\nParameter name: length at the line
int imageIndex = int.Parse(line.Substring(0, delimiter));
Even if in my notepad file I included the image index:
3:What is the foo in the bar?
10:How can you add a widget?
4:Why pick a bar over a foo?
Here is the code:
if (nr >= questions.Count)
{
button1.Enabled = false;
}
else
{
Random r = new Random();
int x;
do
{
x = r.Next(questions.Count);
}
while (questions[x].displayed == true);
textBox1.Text = questionText;
radioButton1.Text = questions[x].answer1;
radioButton2.Text = questions[x].answer2;
questions[x].displayed= true;
current_question = x;
}
You've previously got a line like this:
int delimiter = line.IndexOf(':');
... but you're then not checking the return value. If it's -1, that means your delimiter wasn't found in that particular line - but you're passing it into Substring anyway. Check the value of delimiter before you use it - that way you can throw a more useful exception (or skip the line, or whatever you want to do).
I would actually suggest that you change your code significantly - instead of keeping questions as a List<string> or whatever it is, I'd create a Question class. Parse the lines of text as you read them, discarding failures - or throwing an exception - at that point, rather than waiting until you happen to hit the bad question. You can then have a List<Question> which will make the rest of the code simpler.
You might also want to keep a Queue<Question> which is initially a copy of the complete list, shuffled. When you want to show a new question, just take the next element from that queue. That way you won't need to loop round while you pick already-shown questions. (You'll want to include an Index or QuestionNumber property within the Question class, presumably...)
Note that it's possible that it's working for all the lines that you're really aware of, but that you've got some empty lines at the end of your file. You may well just want to skip empty lines.
Substring parameters are initial index, and length. delimiter from the code does not looks like length.
http://msdn.microsoft.com/en-us/library/aka44szs.aspx
Change following
int delimiter = line.IndexOf(':');
int imageIndex = int.Parse(line.Substring(0, delimiter));
string questionText=line.Substring(delimiter + 1);
pictureBox1.Image = imageList1.Images[imageIndex];
textBox1.Text = questionText;
radioButton1.Text = questions[x].answer1;
questions[x].displayed= true;
current_question = x;
To
int delimiter = line.IndexOf(':');
if(!String.IsNullOrEmpty(line) && delimiter > 0 )
{
int imageIndex = int.Parse(line.Substring(0, delimiter));
string questionText=line.Substring(delimiter + 1);
pictureBox1.Image = imageList1.Images[imageIndex];
textBox1.Text = questionText;
radioButton1.Text = questions[x].answer1;
questions[x].displayed= true;
current_question = x;
}
private string copystring(string instr ,int start ,int length)
{
return instr.Length >= (start + 1)
? (instr.Length > (start + length) ? instr.Substring(start, length) : instr.Substring(start,instr.Length-start))
: "";
}
When I try and run my code I get the error:
Input string was not in a correct format.
I am trying to find the largest int in each line of a text file and then add them all up.
I am sure that there are no letters in this file and everything is separated by a space.
Here is my code:
int counter = 0;
string line;
List<int> col = new List<int>();
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader(label3.Text);
while ((line = file.ReadLine()) != null)
{
int[] storage = new int[10000];
Console.WriteLine(line);
counter++;
string s = line;
string[] words = s.Split(' ');
for (int i = 0; i < words.Length; i++)
{
storage[i] = Convert.ToInt32(words[i]);
}
int large = storage.Max();
col.Add(large);
Console.WriteLine(" ");
foreach (int iii in col)
{
Console.WriteLine(iii);
}
int total = col.Sum();
Console.WriteLine(total);
}
file.Close();
// Suspend the screen.
Console.ReadLine();
It's possible that target string cannot be stored in a 32 bit integer. You can try parsing to ulong type. Take a look at Integral Types Table and Floating-Point Types Table.
Instead of doing Convert.ToInt32(), try int.TryParse(). It will return a bool value telling you if operation succeeded, and it has an out parameter where it will place result of parse operation. TryParse operation is also available on other numeric types if you decide you need them.
E.g.
int val;
string strVal = "1000";
if (int.TryParse(strVal, out val))
{
// do something with val
}
else
{
// report error or skip
}
I did a quick test and it is likely you get the error in the line
storage[i] = Convert.ToInt32(words[i]);
If so, make sure what you are trying to convert is an integer and not an empty string, for example.
I believe that the line in your code that can cause this error is
Convert.ToInt32(words[i]);
Now, when you're running this application in debug mode(which you probably are) in visual studio, you have a way to check what's going on in your program when the exception happens.
At the very very bottom of your screen is going to be some tabs. these tabs include your error list among other things. The ones I like to use are called "Locals" and "Watch". You can use the Locals tab.
When you click on the Locals tab, you should see a tree structure of all the local variables in your program. if you expand the words variable, you should see all the individual members of the array. you should also be able to see the variable i check the i'th member of your words array, and make sure that it's an integer, and not something else.
You're either converting out of size, or attempting to parse a return carriage '/r'
Make sure you're trimming your input.
My solution:
static void Main(string[] args)
{
int linecount = 100;
string path = #"C:\test\test.txt";
Random rand = new Random();
//Create File
StreamWriter writer = new StreamWriter(path, false);
for (int i = 0; i < linecount; i++)
{
for (int j = 0; j < rand.Next(10, 15); j++)
{
writer.Write(rand.Next() + " ");
}
writer.WriteLine("");
}
writer.Close();
//Sum File
long sum = Enumerable.Sum<string>(
(new StreamReader(path)).ReadToEnd().Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries),
l => Enumerable.Max(
l.Split(' '),
i => String.IsNullOrEmpty(i.Trim()) ? 0 : long.Parse(i.Trim())
)
);
}