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

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

Related

Index was outside the bounds of an array? [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 5 years ago.
I'm creating a quick project which takes a .txt from the user, saves each line to an array and then makes a request for each ID, depending if the response contains 'The profile could not be found', or a valid profile, act accordingly.
Here's my code;
static void Main(string[] args)
{
string[] lines = System.IO.File.ReadAllLines(#"C:\\users\\louis\\Desktop\\d.txt");
string[] avaliableIds = { };
string errorMessage = "The specified profile could not be found.</h3><br><br>";
foreach (string c in lines)
{
WebRequest req = WebRequest.Create("http://steamcommunity.com/id/" + c);
WebResponse res = req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
string returne = sr.ReadToEnd();
System.Threading.Thread.Sleep(100);
if (returne.Contains(errorMessage))
{
int avaliableArrayLength = avaliableIds.Length;
int shouldGo = avaliableArrayLength + 1;
avaliableIds[shouldGo] = c;
} // Here is where I'm getting the error
}
for(int i = 0; i == avaliableIds.Length; i++)
{
Console.WriteLine(avaliableIds[i]);
}
}
From what I understand, 'shouldGo' has a higher value than 'avaliableIds', so something is wrong with my declaration, it's supposed to be an array which can hold as high as or as low any number possible.
Please help, thanks.
In C#, arrays have a fixed size. You declare availableIds as an empty (zero-length) array, so you won't be able to store any data in it.
Use a List<string> instead, that's a variable-size data structure.
i == avaliableIds.Length
should be
i < avaliableIds.Length

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

Loading 2 Arrays From Comma Delimited .txt File using Split Method C#

I'm trying to load the data from a comma delimited .txt file and put the information in 2 parallel arrays. The .txt file holds two columns of data, StudentName & StudentGrades.
Its looks similar to this...
Sally,67
Frank,32
John, 98
I'm trying to use the split method to read the comma delimited file, however I've tried many different ways to get this to work with no luck. The error that I am getting is "Cannot implicitly convert type string[] to string"
If I put the .txt data each on seperate lines and remove the split method from the code it works fine. However I need the file to be comma delimited.
public static void LoadArray()
{
StreamReader studentInfoStreamReader = new StreamReader("LittleRecord2.txt");
for (counter = 0; counter < 21; counter++)
{
if (studentInfoStreamReader.Peek() != -1) // CHECK TO SEE IF END OF FILE
{
studentName[counter] = (studentInfoStreamReader.ReadLine().Split(',')); // CODE WITH ERROR
studentGrade[counter] = Convert.ToInt32(studentInfoStreamReader.ReadLine());
}
}
studentInfoStreamReader.Close();
}
public static void OptionOne()
{
LoadArray();
Console.WriteLine("Student Name".ToString().PadRight(20) + ("Student Grade".ToString().PadRight(5)));
Console.WriteLine();
for (int c = 0; c < counter; c++)
{
Console.WriteLine("{0} {1}", studentName[c].PadRight(20), studentGrade[c].ToString().PadRight(5));
}
}
The Split method returns an array. In your case when you split using the comma, it will result in an array with 2 items. The first item at index 0 is the name and the 2nd item at index 1 is the grade:
var splitParts = (studentInfoStreamReader.ReadLine().Split(','));
studentName[counter] = splitParts[0];
studentGrade[counter] = Convert.ToInt32(splitParts[1]);
Instead of parallel arrays, it would be much more efficient to use a class. Also unless your file has millions of entries reading the whole file into memory would probably be much quicker:
class Student
{
public string name = "";
public int grade = 0;
public Student()
{
}
}
List<Student> GetStudents(string fileName)
{
return (from string line in System.IO.File.ReadAllLines(fileName)
let data = line.Split(",".ToArray())
select new Student { name = data[0], grade = int.Parse(data[1]) }).ToList();
}
This is because string.Split() returns an array and you're assigning it to a scalar value. Store the split result in a new array variable and then assign its elements separately:
public static void LoadArray()
{
StreamReader studentInfoStreamReader = new StreamReader("LittleRecord2.txt");
for (counter = 0; counter < 21; counter++)
{
if (studentInfoStreamReader.Peek() != -1) // CHECK TO SEE IF END OF FILE
{
var splitLine = studentInfoStreamReader.ReadLine().Split(',');
studentName[counter] = splitLine[0];
studentGrade[counter] = splitLine[1];
}
}
studentInfoStreamReader.Close();
}
string[] x = studentInfoStreamReader.ReadLine().Split(',');
studentName[counter] = x[0];
studentGrade[counter] = x[1];

c# how to store values from a file in an array [duplicate]

This question already has answers here:
C# parsing a text file and storing the values in an array
(3 answers)
Closed 5 years ago.
I am trying to store values in an array from reading from a file. I have the reading from a file part but I can't get it to store in an array because it gives me an error "Value cannot be null" because after the loop the value of my variable becomes null and the array cannot be null. Here's what I have. And I realize that the for loop probably isn't in the correct spot so any help with where to put it would be great.
Program p = new Program();
int MAX = 50;
int[] grades = new int[MAX];
string environment = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "\\";
string path = environment + "grades.txt";
StreamReader myFile = new StreamReader(path);
string input;
int count = 0;
do
{
input = myFile.ReadLine();
if (input != null)
{
WriteLine(input);
count++;
}
} while (input != null);
for (int i = 0; i < count; i++)
{
grades[i] = int.Parse(input);
}
You start the for loop just after exiting from the while loop. And the condition to exit from the while loop is true when input is null. Of course this is not well accepted by Int.Parse.
Instead you can use a single loop, taking in consideration that you don't want to loop more than 50 times otherwise you exceed the array dimensions
int count = 0;
while((input = myFile.ReadLine()) != null && count < 50)
{
WriteLine(input);
grades[count] = int.Parse(input);
count++;
}
However you can have a more flexible way to handle your input if you use a List<int> instead of an array of integers. In this way you don't have to check for the number of lines present in your file
List<int> grades = new List<int>();
while((input = myFile.ReadLine()) != null)
grades.Add(int.Parse(input));
if we want to get really condensed
var grades = File.ReadAllLines(path).Select(l=>Int.Parse(l)).ToArray();
Utilize the Path.Combine() to help you in concatenating paths.
string environment = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
String fullPath = Path.Combine(environment, "grades.txt");
int[] grades = File.ReadAllLines(fullPath).Select(p => int.Parse(p)).ToArray<int>();
Console.WriteLine(grades);
Refer to https://www.dotnetperls.com/file-readalllines on how to use File.ReadAllLines() its very handy.
I'm using LINQ here, which sometimes simplifies things. Even though it looks a bit intimidating now. We read all lines, the result of that is then parsed by selecting each one and converting it to an integer then outputting an array of integers and saving that to grades.
Program p = new Program();
int MAX = 50;
int[] grades = new int[MAX];
string environment = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "\\";
string path = environment + "grades.txt";
using (StreamReader myFile = new StreamReader(path))
{
string input;
int count = 0;
while((!myFile.EndOfStream) && (count < MAX))
{
input = myFile.ReadLine();
if (!String.IsNullOrWhiteSpace(input))
{
WriteLine(input);
grades[count] = int.Parse(input);
count++;
}
}
}
You should definitely use the "using" pattern around your stream object. Got rid of the for-loop for you while maintaining mostly your code and style. Your issue was that you weren't using the input value before moving on to the next line. You only ever had the last value in your original code.

Count lines in a text without empty liines [duplicate]

This question already has an answer here:
Get total number of non-blank lines from text file?
(1 answer)
Closed 7 years ago.
I'm using next code to count lines in a text i have.
It's work fine but I don't want to count empty lines.
How can I do it, but with saving the current code format?
var lineCount = 0;
using (var readerlines = File.OpenText(strfilename))
{
while (readerlines.ReadLine() != null)
{
lineCount++;
}
}
You can try like this:
int lineCount = File.ReadLines(#"yourfile.txt")
.Count(line => !string.IsNullOrWhiteSpace(line));
Check if the line is not an empty string
var lineCount = 0;
string line = string.Empty;
using (var readerlines = File.OpenText(strfilename))
{
while ((line = readerlines.ReadLine()) != null)
{
if (!line.Equals(string.Empty))
{
lineCount++;
}
}
}
Or this:
string data = File.ReadAllText(strfilename);
string[] lines = data.Split(new char[] {'\n' }, StringSplitOptions.RemoveEmptyEntries);
int line_count = lines.Length;
In short:
int line_count = File.ReadAllText(strfilename).Split(new char[] {'\n' }, StringSplitOptions.RemoveEmptyEntries).Length;

Categories