简体   繁体   中英

Write a C# program to append additional text to an existing file with contents

I am new to C#. I did the following question given below with code and I got the following error described below

question: Write a C# program to append additional text to an existing file with contents. You are given a file named "sentences.txt" with a few lines already stored in it. Create a program to ask the user for several sentences (until they just press Enter) and append them in "sentences.txt". Enter the below contents: "C# supports abstraction and encapsulation. C# supports inheritance and polymorphism." The new content must be appended to its end. Display the entire contents of the text file on the screen.

my code:

using System;
using System.IO;

public class Program      //DO NOT change the class name
{
    //implement code here
    static void Main()
    {
        try
        {
            StreamWriter file = File.AppendText("sentences.txt");
            string line;
            Console.Write("Enter a sentence: ");

            do
            {   
                line = Console.ReadLine();
                if (line != "")
                    file.WriteLine(line);
            }
            while (line != "");
            file.Close();
        }
        catch (Exception)
        {
            Console.WriteLine("Error!!!");
        }
    }
}

this code is not able to read the file elements and not taking the input from the user also. How should I rectify it.

The problem here is that you are writing the same line very very fast many many times to the file, and eventually a cog falls out, probably somewhere around the 2GiB mark. Try moving the line = Console.ReadLine(); to inside the loop.

This is the correct code

using System;
using System.IO;

public class Program      //DO NOT change the class name
{
    //implement code here
    public static void Main()
    {   
        // Creating a file 
        string myfile = @"sentences.txt"; 

        // Appending the given texts 
        Console.WriteLine("Enter the Sentence");
        using(StreamWriter sw = File.AppendText(myfile)) 
        { 
            sw.WriteLine(Console.ReadLine());
            sw.WriteLine(Console.ReadLine());
        } 

        // Opening the file for reading 
        using(StreamReader sr = File.OpenText(myfile)) 
        { 
            string s = ""; 
            while ((s = sr.ReadLine()) != null) { 
                Console.WriteLine(s); 
            } 
        } 
    } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM