Search code examples
c#streamwriter

c# stream writer: how to write numbers on new lines?


i want to make stream writer function where i can write numbers several times and at the end of the program show me sum of those numbers. how i can code this thing?

public static void bought(float a)
    {
        StreamWriter SW = new StreamWriter(@"C:\Users\ETN\source\repos\Apple-store\Apple-store\buy.txt");
        SW.Write(a);
        SW.Close();

    }

Solution

  • There are a couple of things you would want to change in your code. Speficially:

    • You are opening a stream writer, write one value and close it. Unless you already have a list of values you want to write, you generally open and close the stream writer once and call it multiple times.
    • When you want to add a new line after your written value, you use WriteLine instead of Write.
    • When you write numeric values to a text file, they will be converted to text dependent on the culture. Note that the default is the culture of your system. If you read the file from a different computer with a different culture, the file might be unreadable. Therefore you should always provide a specific culture. To do that, check the Convert.ToString method.
    • You should enclose your code that writes to the stream writer in a try/finally block, with the StreamWriter.Close() method in the finally. Otherwise your file is not guaranteed to be closed in the event of an error.
    • It is not recommended to store monetary information (such as prices or account balances) as a float. Use decimal instead, which is optimized for this purpose (as opposed to float which is for scientific calculations).

    This code should give you a head start at the issue. It's up to you to complete it and organize it into methods, classes etc., depending on your specific requirements:

    StreamWriter writer = new StreamWriter(@"C:\Users\ETN\source\repos\Apple-store\Apple-store\buy.txt");
    try {
        while (true) {
            decimal price:
            //Your code that determines the price goes here
            string priceText = Convert.ToString(price, CultureInfo.InvariantCulture);
            writer.WriteLine(priceText);
    
            bool shouldContinue;
            //Your code that determines whether there are more values to be written goes here
            if (!shouldContinue) {
                break;
            }
        }
        writer.Flush();
    }
    finally {
        writer.Close();
    }