Duplication of row while reading from file [duplicate] - c#

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);

Related

Hey I need more information about this code [closed]

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] + " ");
}
}
}

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(...);
}

Insert an Array to a datagidview

I have written a coding which extracts specific lines from a text file, split the lines and insert the data to a gridview. The coding is give below.
Unfortunately, when i execute this program, i receive an error msg called "Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index". Please help me to identify what went wrong in my codings
string line;
System.IO.StreamReader file = new System.IO.StreamReader("test.txt");
while ((line = file.ReadLine()) != null)
{
if (line.Contains("DISKXFER"))
{
string dataLine=line.ToString();
string[] split = dataLine.Split(',');
for (int i = 0; i < split.Length; i++)
{
for (int j = 1; j < dataLine.Length; j++)
{
dataGridView1.Rows[j].Cells[i].Value = split[i];
}
}
}
}
Your DataGridView does not contain the number of rows required to hold the information. Instead of setting dataGridView1.Rows[j].Cells[i] to some value, you need to add one row for every entry in dataLine.
Instead of your nested loop you could do this:
string dataLine=line.ToString();
string[] split = dataLine.Split(',');
dataGridView1.Rows.Add(split);
This page show you an example http://www.dotnetperls.com/convert-list-datatable, for more information about datagridview http://www.dotnetperls.com/datagridview

How to get number of rows in file in C#?

I need to initialize 2D array and first column is every row in a file. How do I get the number of rows in a file?
You could do:
System.IO.File.ReadAllLines("path").Length
Edit
As Joe points out, I left out all the standard error handling and didn't show you would then use this same array to process in the rest of your code.
From MSDN:
int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
Console.WriteLine (line);
counter++;
}
file.Close();
You would have to open the file reading in each line to get the count:
var lines = File.ReadAllLines(filename);
var count = lines.Length;
int counter = 0;
string line;
System.IO.StreamReader file = new System.IO.StreamReader("c:\\t1.txt");
while((line = file.ReadLine()) != null)
{
counter++;
}
file.Close();
counter will give you number of lines. you can insert line into your array as well withthe loop.
There may be a more efficient way for larger files, but you could start with something like:
int l_rowCount = 0;
string l_path = #"C:\Path\To\Your\File.txt";
using (StreamReader l_Sr = new StreamReader(l_path))
{
while (l_Sr.ReadLine())
l_rowCount++;
}
It would probably be more useful for you to actually open the file, read the lines into a List, then create your 2D array.
List<string> lines = new List<string>()
using(System.IO.StreamReader file = new System.IO.StreamReader(fileName))
{
while(!file.EndOfStream) lines.Add(file.ReadLine());
}
You can then use your lines list to create your array.
could you go with something more exotic like a linq statement
Count * from textfile
something like that?

Categories