繁体   English   中英

FileStream参数读/写

[英]FileStream Arguments Read/Write

在C ++中,您可以像这样打开一个流:

int variable = 45;

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

iFile >> variable;

iFile.close

我正在尝试理解C# FileStream 读取和写入方法需要数组和偏移量和计数。 这个数组有多大? 我只是给它任何尺寸,它会填满吗? 如果是这种情况,我该如何使用Filestream读取文件? 我怎么知道我传入的数组有多大?

您可以简单地使用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();
using (FileStream fs = new FileStream("Filename", FileMode.Open))
        {
            byte[] buff = new byte[fs.Length];
            fs.Read(buff, 0, (int)fs.Length);                
        }

请注意,fs.Length很长,所以你必须像int.MaxValue <fs.Length一样检查它。

否则你在while循环中使用旧方法(fs.Read返回读取的实际字节数)

顺便说一句,FileStream不会填满它,但会抛出异常。

在调用.Read方法时,您应该指定和数组,其中将存储结果字节。 因此,此数组长度应至少为(索引+大小)。 写入时,同样的问题,除了这些字节将从数组中获取,而不是存储在其中。

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);
            }
        }

流读取器用于从流中读取文本

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM