FileStream参数读/写

4
在C++中,你可以这样打开一个流:
int variable = 45;

ifstream iFile = new ifstream("nameoffile"); // Declare + Open the Stream
       // iFile.open("nameofIle");

iFile >> variable;

iFile.close

我正在尝试理解C#的FileStream。读取和写入方法需要一个数组、偏移量和计数器。这个数组有多大?我只需要给它任何大小,它就会填充吗?如果是这样,我该如何使用FileStream读取文件呢? 我如何知道传入多大的数组?

4个回答

7

您可以简单地使用StreamReaderStreamWriter包装器来读取和写入:

using(StreamReader sr = new StreamReader(fileName))
{
   var value = sr.ReadLine(); // and other methods for reading
}



using (StreamWriter sw = new StreamWriter(fileName)) // or new StreamWriter(fileName,true); for appending available file
{
  sw.WriteLine("test"); // and other methods for writing
}

或者按照以下方式操作:
StreamWriter sw = new StreamWriter(fileName);
sw.WriteLine("test");
sw.Close();

2
using (FileStream fs = new FileStream("Filename", FileMode.Open))
        {
            byte[] buff = new byte[fs.Length];
            fs.Read(buff, 0, (int)fs.Length);                
        }

请注意fs.Length是long类型,因此您必须像int.MaxValue < fs.Length这样检查它。
否则,您可以在while循环中使用旧方法(fs.Read返回实际读取的字节数)
顺便说一下,FileStream不会填充它,而是会抛出异常。

1

在 FileStream 的 read 方法的参数中,字节数组会从流中读取字节并返回,因此其长度应该与流的长度相等。来自 MSDN

using (FileStream fsSource = new FileStream(pathSource,
            FileMode.Open, FileAccess.Read))
        {

            // Read the source file into a byte array.
            byte[] bytes = new byte[fsSource.Length];
            int numBytesToRead = (int)fsSource.Length;
            int numBytesRead = 0;
            while (numBytesToRead > 0)
            {
                // Read may return anything from 0 to numBytesToRead.
                int n = fsSource.Read(bytes, numBytesRead, numBytesToRead);

                // Break when the end of the file is reached.
                if (n == 0)
                    break;

                numBytesRead += n;
                numBytesToRead -= n;
            }
             numBytesToRead = bytes.Length;

            // Write the byte array to the other FileStream.
            using (FileStream fsNew = new FileStream(pathNew,
                FileMode.Create, FileAccess.Write))
            {
                fsNew.Write(bytes, 0, numBytesToRead);
            }
        }

StreamReader 用于从流中读取文本。


1
在调用 .Read 方法时,您应该指定一个数组,其中将存储结果字节。因此,这个数组的长度应该至少为(Index + Size)。 在写入时,同样的问题,只是这些字节将从数组中获取,而不是存储在其中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接