✅ 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.
using System.IO;
using System.Runtime.CompilerServices;
using Workshop3.Exceptions;
using static System.Net.WebRequestMethods;

namespace Workshop3.IO
{
public class TextFileReader
{

}
}
using System.IO;
using System.Runtime.CompilerServices;
using Workshop3.Exceptions;
using static System.Net.WebRequestMethods;

namespace Workshop3.IO
{
public class TextFileReader
{

}
}
How do i go about solving this?
89 Replies
Angius
Angius2mo ago
uh, make a method and have it read a file?
Merineth 🇸🇪
RIght, but my teachers slides aren't really informative in how i do that
Angius
Angius2mo ago
Google would be File class will be useful
Merineth 🇸🇪
I don't understand, isn't #help supposed to get help with c# coding?
Angius
Angius2mo ago
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
Merineth 🇸🇪
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
Angius
Angius2mo ago
What did you find and why did it not work?
Merineth 🇸🇪
Well afaik i'm supposed to use a mthod from the Using I/O which is Streamreader to read from a textfile.
Angius
Angius2mo ago
It's one way to do that, sure So what didn't work about that?
Merineth 🇸🇪
This is the only information provided around the subject given to us
No description
Angius
Angius2mo ago
So you have pretty much ready-made code Just need to place it inside of a method in the class you were given
Merineth 🇸🇪
Yes, i attempted that earlier and i got 35 errors.
No description
Angius
Angius2mo ago
Notice how I said "inside of a method" While you placed this code inside of a class $structure
MODiX
MODiX2mo ago
namespace Namespace;

[Attribute]
public class Class
{
public string PublicField;
private bool _privateField;

public int PublicProperty { get; set; }

public Class() {} // Constructor

public void Method(int parameter)
{
var localVariable = parameter;

int LocalMethod(string param) { return 3; }
}
}
namespace Namespace;

[Attribute]
public class Class
{
public string PublicField;
private bool _privateField;

public int PublicProperty { get; set; }

public Class() {} // Constructor

public void Method(int parameter)
{
var localVariable = parameter;

int LocalMethod(string param) { return 3; }
}
}
Angius
Angius2mo ago
Here's the naming
Merineth 🇸🇪
I see, so i have to create a method within the class and place the code inside it
Angius
Angius2mo ago
yep
Merineth 🇸🇪
namespace Workshop3.IO
{
public class TextFileReader
{


public void TextFileReaderMethod()
{
using (StreamReader sr = File.Opentext("files/textfile.txt"))
{
string input = null;
while ((input = sr.ReadLine() != null))
{
Console.Writeline(input);
}
}

}
}
}
namespace Workshop3.IO
{
public class TextFileReader
{


public void TextFileReaderMethod()
{
using (StreamReader sr = File.Opentext("files/textfile.txt"))
{
string input = null;
while ((input = sr.ReadLine() != null))
{
Console.Writeline(input);
}
}

}
}
}
Angius
Angius2mo ago
That should work, yes
Merineth 🇸🇪
That did reduce the amount of errors significantly, yea
Merineth 🇸🇪
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 usingstatements
Angius
Angius2mo ago
Delete this line
No description
Merineth 🇸🇪
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 output
Merineth 🇸🇪
Essentially i navigate the menu to "Read Text FIle", insert the number 2 but not getting any output hmm
No description
SG97
SG972mo ago
is your method actually being called? I see 0 references
Merineth 🇸🇪
Good question I'm not entirely sure to be honest
SG97
SG972mo ago
then it probably is not
Merineth 🇸🇪
Should the method be called within the same class?
SG97
SG972mo ago
well, that depends, but it depends even more on how you are handling those 1 and 2 inputs probably not within this class
Merineth 🇸🇪
Ah I see, then I most likely will have to navigate to the namespace where the menus are being handled
SG97
SG972mo ago
assuming the class, but sure
Merineth 🇸🇪
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?
Angius
Angius2mo ago
Basically Except you probably meant fields and properties, not attributes Strictly speaking $structure
MODiX
MODiX2mo ago
namespace Namespace;

[Attribute]
public class Class
{
public string PublicField;
private bool _privateField;

public int PublicProperty { get; set; }

public Class() {} // Constructor

public void Method(int parameter)
{
var localVariable = parameter;

int LocalMethod(string param) { return 3; }
}
}
namespace Namespace;

[Attribute]
public class Class
{
public string PublicField;
private bool _privateField;

public int PublicProperty { get; set; }

public Class() {} // Constructor

public void Method(int parameter)
{
var localVariable = parameter;

int LocalMethod(string param) { return 3; }
}
}
Merineth 🇸🇪
Hmm weird our teacher strictly says it’s attributes 😭
Angius
Angius2mo ago
Your teacher should not be teaching, then Which is how it usually is, unfortunately
Merineth 🇸🇪
Does C# have similar functions such as scanf in C?
Angius
Angius2mo ago
What does scanf do?
Merineth 🇸🇪
Relatable 😭 It's essentially, a user inputs data and we store the data
Angius
Angius2mo ago
Console.ReadLine() for example
Merineth 🇸🇪
Aaah right, nice! Does that prompt an input from the user?
Angius
Angius2mo ago
yep
Merineth 🇸🇪
Okay so i found the corresponding menu
Merineth 🇸🇪
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?
namespace Workshop3.IO
{
public class TextFileReader
{

string filepath = @"C:\Users\joal22za\OneDrive - Jonkoping University\OOP\Workshop3\Workshop3\files\textfile.txt";

void method()
{
string[] lines = File.ReadAllLines(filepath);
}

}
}
namespace Workshop3.IO
{
public class TextFileReader
{

string filepath = @"C:\Users\joal22za\OneDrive - Jonkoping University\OOP\Workshop3\Workshop3\files\textfile.txt";

void method()
{
string[] lines = File.ReadAllLines(filepath);
}

}
}
I also attempted something like this Didn't work tho
canton7
canton72mo ago
What makes you think that it didn't work?
Merineth 🇸🇪
When i input 2 into the menu, nothing happens
Merineth 🇸🇪
If i press enter now, nothing happens
canton7
canton72mo ago
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!
Merineth 🇸🇪
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"
canton7
canton72mo ago
Well, code ain't going to be called if you don't call it
Merineth 🇸🇪
I see. So i have to make sure it's called within the manu when 2 is selected?
canton7
canton72mo ago
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
Merineth 🇸🇪
I found the solution provided by the teacher.
Merineth 🇸🇪
And yes, it seems she has modified the "ReadTextFileMenu.cs" Without mentioning in the description of the assignment that we have to do that :)
namespace Workshop3.Menus
{
public class ReadTextFileMenu : Menu
{
public ReadTextFileMenu(string name)
: base(name)
{
Add(new MenuItem("Read Text File", new Command<ReadTextFileMenu>(this, r => r.ReadTextFile())));
}

public void ReadTextFile()
{
// Clear the console from previous text
Console.Clear();
// Asking the user for filepath
Console.WriteLine("Enter filepath..");
// Saving the filepath as a string object
string filepath = Console.ReadLine();
}
}
}
namespace Workshop3.Menus
{
public class ReadTextFileMenu : Menu
{
public ReadTextFileMenu(string name)
: base(name)
{
Add(new MenuItem("Read Text File", new Command<ReadTextFileMenu>(this, r => r.ReadTextFile())));
}

public void ReadTextFile()
{
// Clear the console from previous text
Console.Clear();
// Asking the user for filepath
Console.WriteLine("Enter filepath..");
// Saving the filepath as a string object
string filepath = Console.ReadLine();
}
}
}
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?
Merineth 🇸🇪
What does this error mean?
canton7
canton72mo ago
The method is defined inside TextFileReader. You're trying to call that as if it was defined on ReadTextFileMenu
Merineth 🇸🇪
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
namespace Workshop3.Menus
{
public class ReadTextFileMenu : Menu
{
public ReadTextFileMenu(string name)
: base(name)
{
Add(new MenuItem("Read Text File", new Command<ReadTextFileMenu>(this, r => r.ReadTextFile())));
}

public void ReadTextFile()
{
// Clear the console from previous text
Console.Clear();
// Asking the user for filepath
Console.WriteLine("Enter filepath..");
// Saving the filepath as a string object
string filepath = Console.ReadLine();

// Call the method inside TextFileReader.cs
TextFileReader.StreamTextFile(filepath);


}
}
}


namespace Workshop3.IO
{
public class TextFileReader
{
public static void StreamTextFile(string filepath)
{
string str = File.ReadAllText(filepath);
Console.WriteLine(str);
}
}
}
namespace Workshop3.Menus
{
public class ReadTextFileMenu : Menu
{
public ReadTextFileMenu(string name)
: base(name)
{
Add(new MenuItem("Read Text File", new Command<ReadTextFileMenu>(this, r => r.ReadTextFile())));
}

public void ReadTextFile()
{
// Clear the console from previous text
Console.Clear();
// Asking the user for filepath
Console.WriteLine("Enter filepath..");
// Saving the filepath as a string object
string filepath = Console.ReadLine();

// Call the method inside TextFileReader.cs
TextFileReader.StreamTextFile(filepath);


}
}
}


namespace Workshop3.IO
{
public class TextFileReader
{
public static void StreamTextFile(string filepath)
{
string str = File.ReadAllText(filepath);
Console.WriteLine(str);
}
}
}
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 ReadAllText
Becquerel
Becquerel2mo ago
you 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.
Becquerel
Becquerel2mo ago
file.readalltext is essentially a convenient wrapper over this IIRC
Merineth 🇸🇪
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 ?
Merineth 🇸🇪
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?
Angius
Angius2mo ago
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
Pobiega
Pobiega2mo ago
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.
Merineth 🇸🇪
Well asking how to go about solving something hardly counts as being spoon-fed Especially someone being completely new to c#
Pobiega
Pobiega2mo ago
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
Merineth 🇸🇪
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
Pobiega
Pobiega2mo ago
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"?
Merineth 🇸🇪
I think i get what you mean, i'm currently trying to relocate the exception handling towards when the user inputs the filepath
Pobiega
Pobiega2mo ago
👍
Merineth 🇸🇪
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
Merineth 🇸🇪
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?
No description
Merineth 🇸🇪
does the sr object become restricted inside the try block?
Pobiega
Pobiega2mo ago
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?
Merineth 🇸🇪
Hmm. Well my suspicion would be to move the try block towards the input of the to check if the filepath exists
Pobiega
Pobiega2mo ago
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?
Merineth 🇸🇪
Oh maybe just a simple ifstatement? I looked it up. Seems there is a method called File.Exists
Pobiega
Pobiega2mo ago
Sure is!
Merineth 🇸🇪
Which seems to return a boolean
Pobiega
Pobiega2mo ago
sure does!
Merineth 🇸🇪
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!!
Pobiega
Pobiega2mo ago
Very nice
Merineth 🇸🇪
How do i mark post as solved?
Pobiega
Pobiega2mo ago
The same way you did last time. /Close
Want results from more Discord servers?
Add your server