FileStream参数读/写

时间:2011-01-11 08:51:28

标签: c# file-io

在C ++中,你打开一个像这样的流:

int variable = 45;

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

iFile >> variable;

iFile.close

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

4 个答案:

答案 0 :(得分: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();

答案 1 :(得分:2)

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不会填满它,但会抛出异常。

答案 2 :(得分:1)

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

答案 3 :(得分: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用于从流中读取文本