C# Equivalent to ifstream/ofstream in C++
Solution 1
FileStream
is what you want. Take a look at the MSDN example on stream composition here.
Solution 2
I feel that StreamReader/StreamWriter offer similar functionality to c++'s ifstream/ofstream. FileStream is for dealing with byte[] data, whereas StreamReader/StreamWriter deal with text.
var writer = new StreamWriter(File.OpenWrite("myFile.txt");
writer.WriteLine("testing");
writer.Close();
var reader = new StreamReader(File.OpenRead("myFile.txt");
while ( !reader.EndOfStream )
{
var line = reader.ReadLine();
}
AmbiguousX
I am a beginner programmer, currently working on a bachelor's degree in Computer Science with a Management Minor. I don't really have an "expertise" in any particular language(s), being as I am still a beginner. However, of the languages, I do have the most experience with C++, C#, and (even though it is not a very "up-to-date" language) Ada. I love learning new things and solving various problems/puzzles.
Updated on June 04, 2022Comments
-
AmbiguousX almost 2 years
I know this has probably been asked before, but I can't find it here on SO anywhere, and I can't get a clear answer on anything I look up on Google either.
I need to know the C# equivalent to C++'s ifstream/ofstream.
For instance, if I had the following C++ code:
ifstream input("myFile.txt"); ofstream output; output.open("out.txt");
What would be the C# equivalent?
I found a site that said (for the in file portion, anyway) that the equivalent was this:
using System.IO; FileStream fs = new FileStream("data.txt", FileMode.Open, FileAccess.Read);
I tried putting this in:
FileStream fs = new FileStream(input, FileAccess.Read);
I don't have the "FileMode" in mine because VS didn't recognize it. And "input" is a string in the parameters that holds the string value of the input file name (for example - "myFile.txt").
I know I've got to be missing something silly and minor, but I can't figure out what that is. Any help on this would be much appreciated!
I'm developing in VS2010, C#-4.0, WPF API.