C
C#15mo ago
Dinny

✅ c# input and output files

So I am trying to design a code that calculates the area of a triangle giving the values in an input file. the answer will appear in the output file and “invalid” if imported values are entered. the code isn’t crashing, but nothing appears in the output file and idky
No description
8 Replies
mtreit
mtreit15mo ago
What type is writer? Make sure you dispose it before the program exits to ensure it flushes to disk. Assuming it's a StreamWriter Usually the best practice for that is to use using to ensure it gets disoposed when it goes out of scope.
using System;
using System.IO;

var file = @"c:\temp\foo.txt";

Console.WriteLine("Let's write the file!");

using (var sw = new StreamWriter(file))
{
sw.WriteLine("Foo");
sw.WriteLine("Bar");
} // sw goes out of scope here and the data is flushed to disk.

Console.WriteLine("Let's read the file!");

// Alternate syntax, will be disposed when we reach the end of the function, in this case
// when the program exits because we are in the Main function.
using var sr = new StreamReader(file);

while (sr.ReadLine() is string line)
{
Console.WriteLine(line);
}
using System;
using System.IO;

var file = @"c:\temp\foo.txt";

Console.WriteLine("Let's write the file!");

using (var sw = new StreamWriter(file))
{
sw.WriteLine("Foo");
sw.WriteLine("Bar");
} // sw goes out of scope here and the data is flushed to disk.

Console.WriteLine("Let's read the file!");

// Alternate syntax, will be disposed when we reach the end of the function, in this case
// when the program exits because we are in the Main function.
using var sr = new StreamReader(file);

while (sr.ReadLine() is string line)
{
Console.WriteLine(line);
}
outputs:
[16:43:37] ✓ dotnet run
Let's write the file!
Let's read the file!
Foo
Bar
[16:43:37] ✓ dotnet run
Let's write the file!
Let's read the file!
Foo
Bar
Dinny
DinnyOP15mo ago
oh yeah it’s stream writer, it’s above the code presented, my mistake tho i forgot to close the files so it was an endless loop 😭😭 i’m so embarrassed to have such a simple error ty for ur help :3
Mayor McCheese
Mayor McCheese15mo ago
Get used to that Simple errors trip you up the most
Dinny
DinnyOP15mo ago
i spent two hours looking for an error when i just didn’t a semicolon 😭😭
JakenVeina
JakenVeina15mo ago
I've done equivalent things, recently it'll never stop, no one's gonna judge you for it get yourself a drink and move on 😉
Omnissiah
Omnissiah15mo ago
wasn't that reported as an error by the ide
Dinny
DinnyOP15mo ago
i didn’t bother to look at the bottom part of the console to see errors listed 🥲🥲 it was my first time writing a program too so i was in my head w everything the only reason i noticed was bc i jotheeed to look down bothered lmao
Accord
Accord15mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server