# what is the best way to read and wtite a single line to a text file?

I have the following code to read a line from a text file.
In the UpdateFile() method I need to delete the existing one line and update it with a new line.
Can anybody please provide any ideas?
Thanks.
FileInfo JFile = new FileInfo(@"C:\test.txt");
using (FileStream JStream = JFile.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
{
int n = GetNUmber(JStream);
MessageBox.Show(n.ToString());
n = n + 1;
UpdateFile(JStream);

}

private int GetNUmber(FileStream jstream)
{
string line = sr.ReadToEnd().Trim();
int result;
if (string.IsNullOrEmpty(line))
{
return 0;
}
else
{
int.TryParse(line, out result);
return result;
}
}

private int UpdateFile(FileStream jstream)
{

}

###### Who is Participating?

Commented:
Try this:
private int UpdateFile(FileStream jstream)
{
jstream.Seek(0, SeekOrigin.Begin);

StreamWriter writer = new StreamWriter(jstream);

writer.WriteLine("new data");

return 0; // whatever value is meaningful to your application
}

0

Fixer of ProblemsCommented:
If that is JAVA, you need to "Request Attention" and get the zones changed for your question.
0

Commented:
If that is JAVA, you need to "Request Attention" and get the zones changed for your question.
Looks like C# code to me  ; )
0

Author Commented:
sorry, forgot to mention C# in my question. Thanks for the answer. I will try and let you know.

Thank you.
0

Fixer of ProblemsCommented:
You're fine, I didn't recognize it so I asked.  We've gotten a lot of questions in the wrong zones recently.  Questions in the wrong zones don't get much response because the right people aren't looking at them.
0

progCommented:
For editing flat text files, it is usually considered that you need to read in the entire file and then output it again, which is ok if the file is not too large.
0

Author Commented:
I tried the code below but it is not writing anything to the file.

Also, the file is very small just to maintain one number in one line. I need to update that one line with a number that gets generated everytime I launch the application.
How can we update that single line? any ideas please?

Thank you.
jstream.Seek(0, SeekOrigin.Begin);
StreamWriter writer = new StreamWriter(jstream);
writer.WriteLine(n.ToString());
MessageBox.Show("file updated");

0

Commented:
I tried the code below but it is not writing anything to the file.
If you never close the stream, then nothing will be written. You can do either of the following (but you should be closing your stream somewhere even if you use the first example).

jstream.Seek(0, SeekOrigin.Begin);
StreamWriter writer = new StreamWriter(jstream);
writer.WriteLine(n.ToString());
writer.Flush();
MessageBox.Show("file updated");


OR
jstream.Seek(0, SeekOrigin.Begin);
StreamWriter writer = new StreamWriter(jstream);
writer.WriteLine(n.ToString());
writer.Close();
MessageBox.Show("file updated");

0

Author Commented:
Thanks for correcting me.
Now I am trying these two methods to read and write to file. Reading is working fine but I get an error message when writing to file. It says "Stream was not writable". I dont get what I am missing.

Thanks again.
private int GetJBBSNUmber(FileStream jbbsstream)
{
try
{
{
jbbsstream.Seek(0, SeekOrigin.Begin);
string line = sr.ReadLine();
int result;
if (string.IsNullOrEmpty(line))
{
return 0;
}
else
{
int.TryParse(line, out result);
return result;
}
}
}
catch (Exception x)
{
throw new Exception(string.Format("Error when reading the JBBS number from file. {0}", x.Message));
}
}

private void UpdateJBBSNumber(FileStream jbbsstream, int n)
{
try
{
using (StreamWriter writer = new StreamWriter(jbbsstream))
{
jbbsstream.Seek(0, SeekOrigin.Begin);
writer.WriteLine(n);
writer.Flush();
MessageBox.Show("file updated");
}
}
catch (Exception x)
{
throw new Exception(string.Format("Error when writing the JBBS number to file. {0}", x.Message));
}
}

0

Commented:
To save from all this seeking business, let's try opening in each function. It doesn't sound like you're going to have much I/O going on (correct me if I'm wrong). "using" statements used on Stream objects automatically close the streams.
FileInfo JFile = new FileInfo(@"C:\test.txt");

int n = GetNUmber(JFile.Name);
MessageBox.Show(n.ToString());
n = n + 1;
UpdateFile(JFile.Name, n);

...

private int GetNUmber(string filename)
{
{
string line = sr.ReadLine();
int result;

int.TryParse(line, out result);

return result;
}
}

private int UpdateFile(string filename, int n)
{
using (StreamWriter sw = new StreamWriter(filename))
{
sw.WriteLine(n.ToString());
}
}

0

Commented:
Correction (to line 12):
FileInfo JFile = new FileInfo(@"C:\test.txt");

int n = GetNUmber(JFile.Name);
MessageBox.Show(n.ToString());
n = n + 1;
UpdateFile(JFile.Name, n);

...

private int GetNUmber(string filename)
{
{
string line = sr.ReadLine();
int result;

int.TryParse(line, out result);

return result;
}
}

private int UpdateFile(string filename, int n)
{
using (StreamWriter sw = new StreamWriter(filename))
{
sw.WriteLine(n.ToString());
}
}

0

Commented:
P.S.

int.TryParse() will ignore spaces and if it happens to receive empty string, then your "out" value will still be zero. This is the reason why I trimmed the code a bit  : )
0

Author Commented:
Unfortunately, I can't use the filename as a parameter to GetNUmber() and UpdateFile(). Because I need to lock the file so it will be accessed only by one user (one process) at a time. So I had to create the stream using FileShare.None option. It looks like I need to manage using streams.
Thanks for the help.

FileInfo JFile = new FileInfo(@"C:\test.txt");
using (FileStream JStream = JFile.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
{
int n = GetNUmber(JStream);
MessageBox.Show(n.ToString());
n = n + 1;
UpdateFile(JStream);

}
0

Author Commented:
Now I tried to do reading and writing in line without using separate functions. It is working fine. Please notice that I am assigning "null" to reader and writer objects. I am not quite sure if it is okay to do this? or should I use close() method?

writer = null;
FileInfo JBBSFile = new FileInfo(@"C:\code\dot NET\CCMC\Core\BalanceBridge\Bankway\Calyx\jbbs.txt");
using (FileStream JBBSStream = JBBSFile.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
{
StreamWriter writer = null;
try
{
int n;
int.TryParse(line, out n);

n = n + 1;

writer = new StreamWriter(JBBSStream);
JBBSStream.Seek(0, SeekOrigin.Begin);
writer.WriteLine(n);
writer.Flush();
}
catch (Exception x)
{
string message = string.Format("Error while processing the file. {0}", x.Message);
System.Windows.Forms.MessageBox.Show(message);
}

writer = null;
}

0

Author Commented:
Please correct me or suggest me. I am just trying different ways.

Thanks.
0

Commented:
Now I tried to do reading and writing in line without using separate functions. It is working fine. Please notice that I am assigning "null" to reader and writer objects. I am not quite sure if it is okay to do this? or should I use close() method?
That should be fine. I thought you had a requirement to do the work in two different methods.

Assigning "null" shouldn't be necessary (but doesn't hurt anything) since the reader and writer will be garbage collected whenever there are no more references to the objects. The references you have will be discarded once the function goes out of scope.

Calling Close() is done for you when you use a "using" constructs (at least with Streams and database connections). There shouldn't be a need to explicitly call it.
0

Author Commented:
Thank you for all the help you provided. Now it is working fine.
0

Commented:
NP. Glad to help  = )
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.