Reading from a textfile

How does it work? Everywhere I look it’s different
17 Replies
Merineth 🇸🇪
I assume it has something to do with streamreader?
Angius
Angius2mo ago
Sure, there are multiple ways to read a file Usually it comes down to either reading the entire file into memory at once, or reading it as a stream so it doesn't fill up the RAM if you're reading something that's 8 gigs
Merineth 🇸🇪
If I’m reading a simple text file, I assume I don’t need streamreader since it’s a tiny textfile?
Angius
Angius2mo ago
Yeah Just var text = await File.ReadAllTextAsync("file.txt") will do Or even the synchronous version if needs must
Merineth 🇸🇪
It says ‘await’ operator can only be used when contained within a method or lambda expression marked with the async modifier We haven’t been taught lambda expression yet
Angius
Angius2mo ago
Yep, that's true Nothing to do with lambdas All to do with async await can only be used inside of an async method If you haven't covered async/await yet, just use the synchronous version of this method
var text = File.ReadAllText("file.txt");
var text = File.ReadAllText("file.txt");
Merineth 🇸🇪
“Var can only appear within a declaration of script code” “File is an ambiguous reference between …” I’m getting to many errors Is there a simple guide to how to manipulate files? It shouldn’t be this hard or complicated in c#
Angius
Angius2mo ago
Those are some weird errors And you're right, it shouldn't be complicated
var text = File.ReadAllText("file.txt");
Console.WriteLine(text);
var text = File.ReadAllText("file.txt");
Console.WriteLine(text);
is a complete and ready C# code that will read the file and show it's contents when ran with dotnet run Post your code, let's see what's wrong
Merineth 🇸🇪
System.IO Is the namespace which contains all the base classes for reading and writing to/from files; right?
Angius
Angius2mo ago
ye
Merineth 🇸🇪
I can’t post my code since I’m at uni
Pobiega
Pobiega2mo ago
That means you are writing the code outside of a method, so its not the code itself, its where you typed it
Merineth 🇸🇪
The class I’m working in isn’t the main Ugh guess I’ll just wait until I get home ig
Angius
Angius2mo ago
Chances are, the issue is what Pobiega said You're trying to use this as a default value of a field or some such In that case, you should specify the type explicitly instead of using var
Merineth 🇸🇪
And tjat would be string? Console.writeline does not exist in the current context
Pobiega
Pobiega2mo ago
Seems like you are getting ahead of yourself, and being unable to share code means we cant really help if you put those two lines of code in Main, it would just work its also fine to put them in another method, and call that method from Main
Merineth 🇸🇪
Mhm I’ll return later ig
Want results from more Discord servers?
Add your server