Arguments FileStream Read / Write

In C ++, you open a stream as follows:

int variable = 45; ifstream iFile = new ifstream("nameoffile"); // Declare + Open the Stream // iFile.open("nameofIle"); iFile >> variable; iFile.close 

I am trying to understand C # FileStream . Reading and writing methods require an array, offset, and count. This array, how big is the array? Am I just giving him some size and will he fill it? If so, how do I go about reading a file using FileStream ? How to find out how large the array I enter is?

+4
source share
4 answers

You can simply use StreamReader and StreamWriter to read and write:

 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 } 

or follow these steps:

 StreamWriter sw = new StreamWriter(fileName); sw.WriteLine("test"); sw.Close(); 
+7
source
 using (FileStream fs = new FileStream("Filename", FileMode.Open)) { byte[] buff = new byte[fs.Length]; fs.Read(buff, 0, (int)fs.Length); } 

Note that the length of fs.Length is long, so you should check it as int.MaxValue <fs.Length.

Otherwise, you use the old method in the while loop (fs.Read returns the actual number of bytes read)

By the way, FileStream does NOT fill it, but instead throws an Exception.

+2
source

When calling the .Read method, you must also specify an array in which the resulting bytes will be stored. Thus, the length of this array should be at least (index + size). During recording, the same problem, except that these bytes will be received from the array, and not stored inside it.

+1
source

The byte array in the arguments of the FileStream read method will receive bytes from the stream after reading, so the length should be equal to the length of the stream. From 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); } } 

The stream player is used to read text from a stream.

+1
source

Source: https://habr.com/ru/post/1335051/


All Articles