3

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.

4

2 回答 2

4

FileStream是你想要的。在此处查看有关流组合的 MSDN 示例。

于 2011-01-12T19:09:20.013 回答
1

我觉得 StreamReader/StreamWriter 提供了与 c++ 的 ifstream/ofstream 类似的功能。FileStream 用于处理 byte[] 数据,而 StreamReader/StreamWriter 用于处理文本。

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();
}
于 2012-11-04T18:08:03.377 回答