Reputation: 65
I am quite new to C# and I am trying to work with files. Right now I have only been calling from a file.
I am coming from Java so most of this is familiar. But I can't get a hold of this error:
StreamReader config = new StreamReader("config.txt");
String test = config.ReadLine();
String cow = File.ReadLines("config.txt").Skip(3).Take(1).First();
Console.WriteLine(cow);
config.WriteLine("text test");
// ^ERROR^
Under "WriteLine" I get an error saying:
"'System.IO.StreamReader' does not contain a definition for 'WriteLine' and no extension method 'WriteLine' accepting a first argument of type 'System.IO.StreamReader' could not be found (are you missing a using directive or an assembly reference?)
I am pretty sure I am not missing a using directive because I have:
using System.IO;
If you have any questions or info please let me know, thanks!
Upvotes: 0
Views: 5373
Reputation: 15294
As the name suggest, StreamReader
reads a stream of bytes, in your case, those bytes happen to represent characters which in turn forms a String
.
File.ReadLines()
uses the StreamReader
behind the scenes to read every line of a specified file, returning an IEnumerable<string>
. Since you're using File.ReadLines()
, there is no reason to be declaring a StreamReader
variable since you're not actually using it to read the file.
Now from what I understand, what you're attempting to do is write to your configuration file again. To do this, you will need to use the StreamWriter
which you can use like this.
const string ConfigurationFilePath = "config.txt";
using(StreamWriter writer = new StreamWriter(ConfigurationFilePath))
{
writer.WriteLine("text test");
}
Upvotes: 4
Reputation: 396
Yes, as others have mentioned the StreamReader is for reading. Here is an example of the SteamWriter in action:
System.IO.StreamWriter file = new System.IO.StreamWriter("config.txt", true);
file.WriteLine("text test");
file.Close();
Upvotes: 3
Reputation: 6565
StreamReader
is for reading files, what you need is StreamWriter
.
Here's a simple tutorial to get you started.
Upvotes: 1