C # Reading and Writing of file streams,
During work, cross-platform transfer of files uses file streams and reads files on the computer to the program memory. Conversely, it is common to store data in the memory as files. make a simple application example.
1. Write the memory data to a computer file.
Const string path = @ "D: \ text.txt"; // path for saving the file
String content = "File content !!!! "; // Define the data in the memory
Byte [] bytes = Encoding. Default. GetBytes (content); // convert the binary data Encoding format to Encoding. Default
Int length = bytes. Length; // The length of the data to be written if you want to write the complete data
Using (FileStream stream = new FileStream (path, FileMode. Create ))
{
Stream. Write (bytes, 0, length); // Write
}
2. "read" the data in the computer file to the memory.
Const string path = @ "D: \ text.txt"; // the file to read the data. The previously written file is used as an example.
Byte [] bytes; // create the object for reading the result
Using (FileStream stream = new FileStream (path, FileMode. Open ))
{
Bytes = new byte [stream. Length]; // you can determine the Length of the read result.
Stream. Read (bytes, 0, bytes. Length); // Read operation
}
String result = Encoding. Default. GetString (bytes); // it is best to convert the read result to the same Encoding format as the written Encoding format to prevent garbled characters.
Console. Write (result );
3. Use the "read" and "write" operations of the file stream to implement a COPY-like function to print the COPY progress.
String rPpath = @ "D: \ song of ice and fire: power game .game.of.thrones.2016.s06e03.hd720p.x264.aac.chs-eng.dytt.mp4"; // The C drive of my computer has such a video
String wPath2 = @ "E: \ A.mp4"; // I want to write it to the edisk.
Byte [] bytes; // defines the binary type of the container to be written and read.
Using (FileStream rStream = new FileStream (rPpath, FileMode. Open ))
{
Bytes = new byte [rStream. Length]; // read all
RStream. Read (bytes, 0, bytes. Length );
}
Using (FileStream wStream = new FileStream (wPath2, FileMode. Create ))
{
Int num = bytes. Length/(1024*1024); // the size of each read is 1 MB.
For (int I = 0; I <= num; I ++)
{
WStream. Write (bytes, 0, num );
I ++;
Console. Write (Math. Round (I/(float) num), 2); // print the read Percentage
Console. Write ("\ n ");
}
}