Hey I need more information about this code [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
private void Button4_Click(object sender, EventArgs e) {
string start = Directory.GetCurrentDirectory() + #"\Sav1.txt";
using(var streamReader = new StreamReader(start)) {
string line = streamReader.ReadLine();
int[] values = line.Split(' ').Select(int.Parse).ToArray();
Array.Sort(values);
Array.Reverse(values);
for (int i = 0; i < values.Length; i++) {
richTextBox4.AppendText(values[i] + " ");
}
}
}
Hey guys I need more information about this code. Could anyone explain me how it works. I mostly googled it so dont know how it works. Also I have added .txt file and got access to first row, but i need to get into 7 and 8 row. There's just random numbers in that .txt file.

Ok so there's a better way to do this. StreamReader has a .Peek() method that is extremely useful for reading to the end of a file. Basically the only thing you're missing is a way to loop through each line in your file.
Start with your using statement.
using(var streamReader = new StreamReader(start)) {...
//Using statement is a way for you to close your stream after the work
//is completed. This is why you need to get a loop inside of here.
Use a loop to read to the end of a file.
This part is what I'd change in your code. Your Using statement will not loop. You have to tell it to loop. Peek() returns -1 or the next character to be read. So you can use this to your advantage to check if you want to read to the end of file. Review the documentation here. https://learn.microsoft.com/en-us/dotnet/api/system.io.streamreader.peek?view=netframework-4.8
while(streamReader.Peek() > -1)
{...
Then you can split to your array per line by simply reading in each or splitting to a character.
int[] values = streamReader.Readline().Split(' ');
Finally you can do the remainder of your code.
for (int i = 0; i < values.Length; i++) {
richTextBox4.AppendText(values[i] + " ");
}
To break down exactly what is going on in your code. Read each comment line by line to get a basic understanding.
//Button Click Event
private void Button4_Click(object sender, EventArgs e) {
//Finding your file and assigning it as a string.
string start = Directory.GetCurrentDirectory() + #"\Sav1.txt";
//Using a `using` statement and creating a new streamReader that will look
//for the string that you created above to find the file. The using block
//will properly close the streamreader when the work is done.
using(var streamReader = new StreamReader(start)) {
//StreamReader.ReadLine() will read the FIRST line, no loop here.
//This is why your code only reads one.
string line = streamReader.ReadLine();
//Splitting to an array.
int[] values = line.Split(' ').Select(int.Parse).ToArray();
//Sorting array.
Array.Sort(values);
//Reversing the array.
Array.Reverse(values);
//Looping through the array based on count.
for (int i = 0; i < values.Length; i++) {
richTextBox4.AppendText(values[i] + " ");
}
}
}
If you're attempting to only get rows 7, 8, 9, etc.. within your for loop at the very end of your code do the following.
//Looping through the array based on count.
for (int i = 0; i < values.Length; i++) {
//This will only append rows 7-9. Keep in mind an array is a 0 based
//index. Meaning row 7 is actually array element 6. Row 9 is actually
//array element 8.
if(i > 5 && i < 9){
richTextBox4.AppendText(values[i] + " ");
}
}
}
}

So my current code looks like this:
private void Button4_Click(object sender, EventArgs e)
{
string start = Directory.GetCurrentDirectory() + #"\Sav1.txt";
using (var streamReader = new StreamReader(start))
{
while (streamReader.Peek() > -1)
{
string[] values = streamReader.ReadLine().Split(' ');
Array.Sort(values);
Array.Reverse(values);
for (int i = 0; i < values.Length; i++)
{
richTextBox4.AppendText(values[i] + " ");
}
}
}

Related

How do I read in a text file with a loop, line by line [duplicate]

This question already has answers here:
What's the fastest way to read a text file line-by-line?
(9 answers)
Closed 5 years ago.
So I am just starting out C# with little to no knowledge, so this is more for learning for me than practical use. Therefore what I really would like to know is how I can get my code to work my way, even if there is a much simpler/quicker/smarter solution.
So what I wanna do is create a string array, and using a loop read in each line from a text file into a corresponding element of the array. That's what I tried to do here, and I would love to hear what solutions you have for this.
{
class Program
{
static void Main(string[] args)
{
StreamReader ki = new StreamReader("kiserlet.txt");
string[] a = new string[15];
Console.ReadLine();
int y = 0;
int n = 0;
for (int i = 0; i > 15; i++)
{
a[n] = Convert.ToString(ki.ReadLine());
n++;
}
for (int x = 0;x > 15;x++)
{
Console.WriteLine(a[y]);
y++;
}
Console.ReadLine();
ki.Close();
}
}
}
You can read each line of the file into an array, then iterate through it.
class Program
{
static void Main(string[] args)
{
// this will read all lines from within the File
// and automatically put them into an array
//
var linesRead = File.ReadLines("kiserlet.txt");
// iterate through each element within the array and
// print it out
//
foreach (var lineRead in linesRead)
{
Console.WriteLine(lineRead);
}
}
}

Use the "new" keyword to create an object instance [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
Is someone able to help me out with the following please, I'm trying to split data from an input file (2 pieces of data per line, separated by either of the delimiters specified in the code below). To do this I have declared the string array 'split input', however when I run the program I get a runtime error (screenshot) with the split input line inside the while loop highlighted in yellow. I can't see what I am doing wrong, I'm copying sample code which seems to be working fine :(
NB - the messageBox line below the yellow is just for my testing to prove the split worked
private int DetermineArraySize(StreamReader inputFile)
{
int count = 0;
while (!inputFile.EndOfStream)
{
inputFile.ReadLine();
count++;
}
return count;
}
private void ReadIntoArray(StreamReader inputFile, string[] gameArray, int[] revArray)
{
string rawInput;
string[] splitInput = new string[2];
int count = 0;
char[] delimiters = {'=', '#',};
while (!inputFile.EndOfStream || count < gameArray.Length)
{
rawInput = inputFile.ReadLine();
{
splitInput = rawInput.Split(delimiters);
MessageBox.Show(splitInput[0] + " // " + splitInput[1]);
count++;
}
}
}
private void rdGameSalesForm_Load(object sender, EventArgs e)
{
StreamReader inputFile = File.OpenText("GameSales.txt"); //Open Input File
int arraySize = DetermineArraySize(inputFile); //Use input file to determine array size
string[] gameTitle = new string[arraySize]; //Declare array for GameTitle
int[] revenue = new int[arraySize]; ///Declare array for Revenue
ReadIntoArray(inputFile, gameTitle, revenue);
Thanks for your help
Just add check on null.
ReadLine Method returns null if the end of the input stream is reached. It is possible because you check !inputFile.EndOfStream or count < gameArray.Length. So in the second condition has a possibility to get null when input filre reading
while (!inputFile.EndOfStream || count < gameArray.Length)
{
rawInput = inputFile.ReadLine();
if(rawInput !=null)
{
splitInput = rawInput.Split(delimiters);
MessageBox.Show(splitInput[0] + " // " + splitInput[1]);
}
}
Check for null instead of end of stream.
while((rawInput = Inputfile.ReadLine()) != null)
{
splitInput = rawInput.Split(delimiters);
MessageBox.Show(...);
}

How to read a comma position from an Array C# [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Hi I'm Trying o make an atom simulation game where I can read my data from a txt file and use the data for the simulation/game. I have read the file but I am having trouble finding the commaposition from the string array. The txt file looks like this: 1,H,Hydrogen,1,1+
3,Li,Lithium,7,1+
static void Main(string[] args)
{
string commapostition;
string[] list = new string[44];
StreamReader rFile = new StreamReader(#"JUNK1.txt");
for (int i = 0; i < 44; i++)
{
list[i] = rFile.ReadLine();
}
rFile.Close();
for (int i = 0; i < 44; i++)
{
commapostition = list[i].IndexOf(',');
}
}
If each line of your file looks like what you posted:
1,H,Hydrogen,1,1+
And the order Atomic #, Symbol, Name, Mass, Charge is constant, you can do something like this:
static void Main(string[] args)
{
string filename = #"JUNK1.txt";
string[] lines = File.ReadAllLines(fileName);
for (int i = 0; i < lines.Length; i++)
{
string[] entries = lines[i].Split(',');
string atomicNumber = entries[0];
string symbol = entries[1];
string name = entries[2];
string mass = entries[3];
string charge = entries[4];
// Do stuff with these values...
}
}
Assume you have a text file JUNK1.txt with the lines:
1,H,Hydrogen,1,1+
3,Li,Lithium,7,1+
You can read this line as follows:
static void Main(string[] args)
{
// Path to the file you want to read in
var filePath = "path/to/JUNK1.txt";
// This will give you back an array of strings for each line of the file
var fileLines = File.ReadAllLines(filePath);
// Loop through each line in the file
foreach (var line in fileLines)
{
// This will give you an array of all the values that were separated by a comma
var valuesSeparatedByCommas = line.Split(',');
// Do whatever with the array valuesSeparatedByCommas
}
}
After the above code executes for the first line, the variable valuesSeparatedByCommas array will look like the following:
0 1 2 3 4
+---+---+----------+---+----+
| 1 | H | Hydrogen | 1 | 1+ |
+---+---+----------+---+-----
And now you can access each part of the line based on it's index:
// valueAtPosition0 will be '1'
var valueAtPosition0 = valuesSeparatedByCommas[0];
// valueAtPosition1 will be 'H'
var valueAtPosition1 = valuesSeparatedByCommas[1];

Writing Array LineWise to a .txt file?

Here is a small part of my program. here i am basically writing a .txt file when the button - 'HideItBtn' is clicked. in this piece of code first the.txt file is created then the value of the ListView SubItem - 'Folder path' is stored in a string array and that array is used to write the text file.
private void HideItBtn_Click(object sender, EventArgs e)
{
string[] strArray = new string[500];
int i = 0;
//Creat Hide.bat and write in it !
StreamWriter hide = new StreamWriter(HideNameTxt.Text + ".txt");
for (int j = 1; j < FolderList.Items[i].SubItems.Count; j++)
{
ListViewItem.ListViewSubItem cur = FolderList.Items[i].SubItems[j];
strArray[i] = cur.Text;
hide.WriteLine("attrib \" + strArray[i] + "\" + Environment.NewLine);
i++;
}
hide.Close();
}
Now the problem:
i run my application and select 3 folders from which show up in the ListView !
But the output .txt file only contains :
attrib "C:\Users\Sand\Desktop\nf"
Non of the other folder r
listed ! i added -"Environment.NewLine" at the end of .WriteLine ! but nothing happened ! Please Help ! Thanks !
You need to have two for loops, not one. Currently you're incrementing i at the end of your for loop, but you've only written one of the sub items, not all of them. You need to have a loop that goes through all items, and another loop to go through all sub-items.
private void HideItBtn_Click(object sender, EventArgs e)
{
using (StreamWriter hide = new StreamWriter(HideNameTxt.Text + ".txt"))
for (int i = 0; i < FolderList.Items.Count; i++)
for (int j = 1; j < FolderList.Items[i].SubItems.Count; j++)
{
ListViewSubItem cur = FolderList.Items[i].SubItems[j];
hide.WriteLine("attrib \"" + cur.Text + "\""
+ Environment.NewLine);
}
}

Duplication of row while reading from file [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
printing 2d array in c# through for loop
this is how my data in txt file:
1--2--3--
3-4-4-5--
-7-3-4---
7--5--3-6
--7---4--
3-2--4-5-
------3--
2-6--7---
4---4--3-
without any empty line between! have this formatting issue above!
is my c# code to do file reading with the display too:
public void populate_grid_by_file()
{
int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader("data.txt");
for (int i = 0; i < Sodoku_Gri.GetLength(0); i++)
{
while ((line = file.ReadLine()) != null)
{
for (int j = 0; j < Sodoku_Gri.GetLength(1); j++)
{
Sodoku_Gri[i,j] = line[j];
Console.Write(line[j].ToString());
}
Console.WriteLine(line);
counter++;
}
}
file.Close();
// Suspend the screen.
Console.ReadLine();
}
but when i display my array with the file reading above it is like:
1--2--3--1--2--3--
3-4-4-5--3-4-4-5--
-7-3-4----7-3-4---
7--5--3-67--5--3-6
--7---4----7---4--
3-2--4-5-3-2--4-5-
------3--------3--
2-6--7---2-6--7---
4---4--3-4---4--3-
cnt understand why duplication! help!
When i debugged i found that there was a problem in the line:
Console.Write(line[j].ToString());
it means that automatically elements are not being loaded into the array here:
Sodoku_Gri[i,j] = line[j];
Kindly help me with this!
You display the line once, character by character here:
Console.Write(line[j].ToString());
And then the full line all at once here:
Console.WriteLine(line);

Categories