For Programmers: Free Programming Magazines  


Home > Archive > C# > September 2005 > Save File problem - A Tricky One for Me









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Save File problem - A Tricky One for Me
Shentho

2005-09-07, 6:59 pm

Hi I am stuck with a problem of saving a file which is data from a text
box on a windows form.

The text of each line is data seperated by '~' for example
here is a sample file contents.

1640797~CSANCHE~DRUIZ~09/01/2004~2005~WIRE~WIRE~TRAVEL DEPOSIT~~
1640798~CSANCHE~DRUIZ~09/01/2004~2005~WIRE~WIRE~TRAVEL DEPOSIT~~
1640799~CSANCHE~DRUIZ~09/01/2004~2005~WIRE~WIRE~TRAVEL~~
1640800~CSANCHE~DRUIZ~09/01/2004~2005~WIRE~WIRE~TRAVEL DEPOSIT~~
1640801~CSANCHE~DRUIZ~09/01/2004~2005~WIRE~WIRE~TRAVEL DEPOSIT~~

I then read the data in line by line and use the String.Split function.

Here is the data creation method

FileStream fs = new FileStream(Logfile,FileMode.Create);
StreamWriter m_sw2 = new StreamWriter(fs,System.Text.Encoding.ASCII);
// Save Data
int i=0;
foreach (string s in textBoxBatch.Lines)
{
m_sw2.WriteLine(s);
}
m_sw2.Flush();
m_sw2.Close();
fs.Close();

Even though I specify Encoding ASCII, the file created is not read in
properly.

When I use the following code to read the data back in
I keep getting a message which states this file only has 1 field.

int L=0;
string s="";
StreamReader sr = File.OpenText(fileName);
while ((s = sr.ReadLine()) != null)
{
Temp = s.Split('~');
L = Temp.Length;
if (L > 5)
{
// Data can be processed
Process(Temp);
}
else // Data is in an invalid format. Processing stopped
{
MessageBox.Show(string.Format("It had only {0} field(s) ",L));
break;
}
}
sr.Close();

I don't know why this is happening, I have another source of data which
looks identical but it reads in the data just fine, so I believe it is
the file creation which is in question.

I would be very happy if someone out there can figure this out?

visar

2005-09-09, 6:59 pm

FileInfo.OpenText returns a new StreamReader with UTF8 encoding. You
can just do:

using (StreamReader sr =3D new StreamReader(fileName))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line =3D sr.ReadLine()) !=3D null)
{
Temp =3D s.Split('~');
L =3D Temp.Length;
if (L > 5)
{
// Data can be processed
Process(Temp);
}
else // Data is in an invalid format.
Processing stopped
{
MessageBox.Show(string.Format(=AD"It
had only {0} field(s) ",L));
break;
}

}
}

Double check the code I have presented, but it should work.

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com