StreamReader??

  • Thread starter Thread starter mario
  • Start date Start date
M

mario

I'm new in C#.
I don't know how to read from the "file.txt" line that is seperated with #
example
name#address
name2#address

and to put that into
class k{
public k(){
string n=null;
string ad=null;
}

public k(string a,string b){
string n=b;
string ad=b;
}
private string n;
private string ad;
}
Do I need frst count \n and create object as many as there are \n??
 
Hi mario,
I don't know how to read from the "file.txt" line that is seperated
with # example
name#address
name2#address

and to put that into
class k{
public k(){
string n=null;
string ad=null;
}

public k(string a,string b){
string n=b;
string ad=b;
}
private string n;
private string ad;
}

First of all ... a better way for your class would be:

class K {

private string _name = String.Empty;
private string _address = String.Empty;

public string Name {
get { return this._name; }
set { this._name = value; }
}

public string Address {
get { return this._address; }
set { this._address = value; }
}

public K() { }

public K( string n, string a ) {
this._name = n;
this._address = a;
}
}

Then, to read the lines from the file, you can use a StreamReader ... and I
would suggest you use an ArrayList for the instances of your K-Class. For
Example:

public ArrayList LoadFile( string fileName ) {

ArrayList result = new ArrayList();

if ( File.Exists( fileName ) ) {
StreamReader sr = new StreamReader();
string line;

while ( (line = sr.ReadLine()) != null ) {
string[] parts = line.Split('#');
result.Add( new K( parts[0], parts[1] );
}
}

return result;
}

You'll need to import the namespaces System.Collections and System.IO
(using). The code reads the textfile line by line and splits every line
there, where the '#' is in two parts, which are then assigned.

Hope I could help ...

Regards,
 
mario said:
I'm new in C#.
I don't know how to read from the "file.txt" line that is seperated with #
example
name#address
name2#address

and to put that into
class k{
public k(){
string n=null;
string ad=null;
}

public k(string a,string b){
string n=b;
string ad=b;
}
private string n;
private string ad;
}

Note that your constructors will never assign anything to the instance
variables, as they declare local variables which hide the instance
variables.
Do I need frst count \n and create object as many as there are \n??

No. Use StreamReader.ReadLine to read each line, then process it and
add the result to an ArrayList.
 
Back
Top