✅ Reading a file
Problem description:
In the file TextFileReader.cs (in the folder IO), you will find a code skeleton for the class
TextFileReader. Implement the functionality to read text from a text file. It should be possi-
ble to use the class from a client (another class), where the client can enter a path to the text file,
where the file’s content is returned to the client. In the folder files (in Solution Explorer ), there
is a text file textfile.txt containing some rows of text. The relative path to this file (from the
code) is files/textfile.txt.
How do i go about solving this?
89 Replies
uh, make a method and have it read a file?
RIght, but my teachers slides aren't really informative in how i do that
Google would be
File
class will be usefulI don't understand, isn't #help supposed to get help with c# coding?
It is, yes
But you're also expected to put in the bare minimum of effort yourself
And it's clear you didn't even google
csharp read file
I'm aware, but i'm completely new to c#
I've been trying to find a solution since 8 am this morning
don't assume anything
What did you find and why did it not work?
Well afaik i'm supposed to use a mthod from the
Using I/O
which is Streamreader
to read from a textfile.It's one way to do that, sure
So what didn't work about that?
This is the only information provided around the subject given to us
So you have pretty much ready-made code
Just need to place it inside of a method in the class you were given
Yes, i attempted that earlier and i got 35 errors.
Notice how I said "inside of a method"
While you placed this code inside of a class
$structure
Here's the naming
I see, so i have to create a method within the class and place the code inside it
yep
That should work, yes
That did reduce the amount of errors significantly, yea
Severity Code Description Project File Line Suppression State
Error CS0104 'File' is an ambiguous reference between 'System.Net.WebRequestMethods.File' and 'System.IO.File
Google mentions that i'm using two using
statementsDelete this line
Oh yeah that fixed the error
Error CS0117 'File' does not contain a definition for 'Opentext'
Ah nvm
was a typo
Okay right it did compile correctly now, i ran the program but i didn't get any outputEssentially i navigate the menu to "Read Text FIle", insert the number 2 but not getting any output hmm
is your method actually being called?
I see 0 references
Good question
I'm not entirely sure to be honest
then it probably is not
Should the method be called within the same class?
well, that depends, but it depends even more on how you are handling those 1 and 2 inputs
probably not within this class
Ah I see, then I most likely will have to navigate to the namespace where the menus are being handled
assuming the class, but sure
Quick question tho about c#.
Can c# generally be summarized as being Classes and objects where each class is a blueprint to instantiate an object with attributes and methods?
Basically
Except you probably meant fields and properties, not attributes
Strictly speaking
$structure
Hmm weird our teacher strictly says it’s attributes 😭
Your teacher should not be teaching, then
Which is how it usually is, unfortunately
Does C# have similar functions such as scanf in C?
What does
scanf
do?Relatable 😭
It's essentially, a user inputs data and we store the data
Console.ReadLine()
for exampleAaah right, nice!
Does that prompt an input from the user?
yep
Okay so i found the corresponding menu
I'm not entirely sure if it's calling it tho?
It should be possible to use the class from a client (another class), where the client can enter a path to the text file,
where the file’s content is returned to the client
Would this indicate that i have to make a Console.ReadLine()
command to accept the filepath to the file the user wants outputted?
I also attempted something like this
Didn't work thoWhat makes you think that it didn't work?
When i input
2
into the menu, nothing happensIf i press enter now, nothing happens
You're not showing us the bit of code which control what happens when you enter '2'...
Ah, it's this
But that's callineg
ReadTextFileManu.ReadTextFile
, which just calls Show
?
I don't see anything which calls TextFileReader
Psychic code FTW!Yeah i'm not sure either, the code given to us is made from our teacher
All i'm meant to do is finish making the code in "TextFileReader.cs"
Well, code ain't going to be called if you don't call it
I see. So i have to make sure it's called within the manu when
2
is selected?If you want it to be called when you select menu item 2, you need to have some code which calls it when you select menu item 2
It ain't gonna call itself. It can't read your mind
I found the solution provided by the teacher.
And yes, it seems she has modified the "ReadTextFileMenu.cs"
Without mentioning in the description of the assignment that we have to do that :)
Okay so i wrote some code myself and i successfully made it so the menu accepts an input from the user
However, now i want it to output all of the text inside the file
How do i call a method inside another class?
Do i just create the method inside the class i want and set it to public? And then call that method?
What does this error mean?
The method is defined inside
TextFileReader
. You're trying to call that as if it was defined on ReadTextFileMenu
Is that not allowed?
Or is it the call to the method within
TextFileReader.cs
that is the problem?
oh woops they have the same name, that might be it
I changed name to "StreamTextFile"
But when i try to call the method it can't find it, hmm
Severity Code Description Project File Line Suppression State
Error CS0120 An object reference is required for the non-static field, method, or property
I added static
to my method and it compiled? Not sure why tho
HOLY i did it
I'm the fucking best
This code worked but i'd love if someone could show me how it would look like if i use ReadStream instead of ReadAllTextyou can find an example of using FileStream on the MS docs: https://learn.microsoft.com/en-us/dotnet/api/system.io.filestream.read?view=net-8.0
FileStream.Read Method (System.IO)
Reads a block of bytes from the stream and writes the data in a given buffer.
file.readalltext is essentially a convenient wrapper over this IIRC
Okay i got it to work. However if the user inputs a path which doesn't exist i get an error
Is it possible to handle this error with an
exception
?Anyone got any idea what i might have done wrong?
It successfully catches the problem, and prints "Filepath does not exist" into the terminal but i'm stillö getting exception unhandled?
I removed the "throw" inside the catch block. But now when the program closes right after. Is it possible for it to return up to the try statement?
Right-click the file that's supposed to be read in VS, open properties, set it to be copied always or copied if newer
Also, it's generally not a good idea to keep your code on OneDrive
You'd normally do that with a loop, but you cant do that here, because the input (the file path) comes from outside. so to let the exception go is the correct thing to do
you'd need to have the loop where you ask the user for the path
Also regarding this comment.. We're not here to spoonfeed you answers. We are here to help you learn. Keep that in mind and you'll be fine.
Well asking how to go about solving something hardly counts as being spoon-fed
Especially someone being completely new to c#
No absolutely not, but ZZZZ has a very valid point in that making a google search before asking isnt too much to ask from our point either.
If you need help understanding what the google results told you, thats fine.
Thats why we always ask you to specify what you have tried, where you got stuck, what you need help with
Yes, that's fine. I should've mentioned what i've tried in the post to clarify.
I wouldn't ask a question without trying myself first, lol
Yeah that would be great 🙂
That unfortunately is not true for many or even most.
But enough of that, you get the point. Did you understand my point above about the re-trying and doing it at the "right place"?
I think i get what you mean, i'm currently trying to relocate the exception handling towards when the user inputs the filepath
👍
By any chance, does visual studio 2022 have an auto formatter for code? I checked the advanced tab and it says CTRL + D or CTRL + F but that doesnt seem to work
I moved the try and catch towards the creating of the streamreader object. However when i do this
sr
changes to The name 'sr' does not exist in the current context
. Why is that the case? Tey both exist in the same namespace and the same class. Shouldn't that be ok?does the
sr
object become restricted inside the try block?sort of. restricted isnt the right word, but you can think about it like that
because
sr
is defined inside a scope, the declaration only exists within that scope
so you could define it outside the try, then initialize it (give it a value) inside the try
however, if the try fails, sr
will still be null so you can't very well read from it
Can you think of a way to solve this problem?Hmm. Well my suspicion would be to move the try block towards the input of the to check if the filepath exists
hint: a try block can contain way more than just a single line of code.
alternatively, can you check if the file exists without using
try
? as in, is there another way that might be easier and not cause the scope issue?Oh maybe just a simple
if
statement?
I looked it up. Seems there is a method called File.Exists
Sure is!
Which seems to return a boolean
sure does!
Nice ! I think i got it to work. Combined an if statement to check if it exists and if not it just retired the same method and asks for an input.
Yeah it seems to work perfectly c:
Thanks!!
Very nice
How do i mark post as solved?
The same way you did last time. /Close