I have a text file with below Format:
John Smith 19 175.7
Jane Smith 18 168.5
.
.
.
that they are first name, last name, age and tall (cm) respectively.
I Created a Class that has 4 fields for those . (string first, string last, int age, float tall)
How Can I Read the file and put them in an instance of my class ?
Please write exact code. I have problem with C# IO :-(
Thanks.
Loading

Kirtan PatelPosted Jul 21, 2010, 12:46 AM
/*start Reading TextFile */
string[] Lines = File.ReadAllLines("data.txt");
foreach (string line in Lines)
{
if (line.Trim() != "")
{
string[] Fields = line.Split(' ');
/* Fill it in Person Class */
Person p = new Person();
p.FirstName = Fields[0];
p.LastName = Fields[1];
p.Age = Convert.ToInt32(Fields[2]);
p.Height = float.Parse(Fields[3]);
}
}
Persons Class
----------------
class Person
{
private string _FirstName;
private string _LastName;
private int _Age;
private float _Height;
public float Height
{
get
{
return _Height;
}
set
{
_Height = value;
}
}
public string FirstName
{
get
{
return _FirstName;
}
set
{
_FirstName = value;
}
}
public string LastName
{
get
{
return _LastName;
}
set
{
_LastName = value;
}
}
public int Age
{
get
{
return _Age;
}
set
{
_Age = value;
}
}
}
Majid KamaliPosted Jul 22, 2010, 2:23 AM
Kirtan PatelPosted Jul 21, 2010, 11:04 PM
if file is too much big you can also use structure like LINKED LIST..to fully utilize the main memory ..to store strings to process
Majid KamaliPosted Jul 21, 2010, 6:56 PM
Kirtan PatelPosted Jul 21, 2010, 8:52 AM
A. line.Trim() != ""
its used because if any string contain extra spaces around it it will remove extra white space from it. so if string is blank we dont need to process ..
B. line.Split(' ')
its used to split the like for example if "this is fox" now if we want word 'this' 'is 'fox' in array thenn we can use split method that will split our sentence in different sections ..and store it part in array it splits it by white space ..so we used Split(' ')
2. Why for converting to int you used Convert.Toint32() and for converting to float you used float.parse() ?
What is difference between them ?
when we split the string its in string format and we need to store it as Integer Value so we converted String Value to Integer using Convert.ToInt32 method
Now convert class have not Convert.ToFloat() method so that we need to convert it using Explicitly ..using type casting to store it in Person.Height variable ...
Majid KamaliPosted Jul 21, 2010, 7:21 AM
A. line.Trim() != ""
B. line.Split(' ')
2. Why for converting to int you used Convert.Toint32() and for converting to float you used float.parse() ?
What is difference between them ?
Thank you :-)