?
Solved

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

Posted on 2011-05-05
18
Medium Priority
?
375 Views
Last Modified: 2012-05-11
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)
        {
            StreamReader sr = new StreamReader(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)
{

}

Open in new window

0
Comment
Question by:ipjyo
  • 8
  • 7
  • 2
  • +1
18 Comments
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 35701865
If that is JAVA, you need to "Request Attention" and get the zones changed for your question.
0
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 2000 total points
ID: 35701882
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
}

Open in new window

0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 35701890
If that is JAVA, you need to "Request Attention" and get the zones changed for your question.
Looks like C# code to me  ; )
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

Author Comment

by:ipjyo
ID: 35702279
sorry, forgot to mention C# in my question. Thanks for the answer. I will try and let you know.

Thank you.
0
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 35702384
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
 
LVL 18

Expert Comment

by:deighton
ID: 35704780
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 Comment

by:ipjyo
ID: 35705978
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");

Open in new window

0
 
LVL 75

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 2000 total points
ID: 35706557
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");

Open in new window


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

Open in new window

0
 

Author Comment

by:ipjyo
ID: 35707080
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
            {
                using (StreamReader sr = new StreamReader(jbbsstream))
                {
                    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));
            }
        }

Open in new window

0
 
LVL 75

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 2000 total points
ID: 35707387
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)
{
    using (StreamReader sr = new StreamReader(jstream))
    {
        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());
    }
}

Open in new window

0
 
LVL 75

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 2000 total points
ID: 35707393
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)
{
    using (StreamReader sr = new StreamReader(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());
    }
}

Open in new window

0
 
LVL 75

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 2000 total points
ID: 35707403
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 Comment

by:ipjyo
ID: 35707438
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 Comment

by:ipjyo
ID: 35707521
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?

reader = null;
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))
                {
                    StreamReader reader = null;
                    StreamWriter writer = null;
                    try
                    {
                        int n;
                        reader = new StreamReader(JBBSStream);
                        string line = reader.ReadLine();
                        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);
                    }

                    reader = null;
                    writer = null;
                }

Open in new window

0
 

Author Comment

by:ipjyo
ID: 35707528
Please correct me or suggest me. I am just trying different ways.

Thanks.
0
 
LVL 75

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 2000 total points
ID: 35708147
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 Comment

by:ipjyo
ID: 35709202
Thank you for all the help you provided. Now it is working fine.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 35710699
NP. Glad to help  = )
0

Featured Post

Get your Disaster Recovery as a Service basics

Disaster Recovery as a Service is one go-to solution that revolutionizes DR planning. Implementing DRaaS could be an efficient process, easily accessible to non-DR experts. Learn about monitoring, testing, executing failovers and failbacks to ensure a "healthy" DR environment.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
In real business world data are crucial and sometimes data are shared among different information systems. Hence, an agreeable file transfer protocol need to be established.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
Suggested Courses
Course of the Month16 days, 21 hours left to enroll

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question