Home > Article > Backend Development > .net streams – file copying using streams
Similar to various file streams and network streams in Java, there are also various types of streams in .net. The main purpose of streams is to interact with files or data sources outside the application. The base class is Stream, defined under the namespace System.IO;
In the test file, write something:
. Note that if you don’t use using, don’t forget to dispose.
## 2. Copy in batches in a loopIn order to test the following code, it is recommended to find a larger file.
#region 使用流进行一次性复制 //创建一个文件流对象(参数一:指定了文件的位置;参数二:枚举值,指定操作系统打开文件的方式;参数三:表明了打开文件的意图;注意第二个参数与第三个参数要注意搭配使用) Stream source = new FileStream(@"C:/Users/v-liuhch/Desktop/StreamTest.txt", FileMode.Open, FileAccess.Read); byte[] buffer = new byte[source.Length]; //将文件数据写入到字节数组中(参数一:要写入的字节数组; 参数二:用于设定文件从哪个位置开始读取;参数三:读取的字节数) int byteRead = source.Read(buffer, 0, (int)source.Length);//返回值为读取到的字节数 //foreach (var b in buffer) //{ // // Console.WriteLine(Convert.ToString(b, 2));//二进制 // //Console.WriteLine(Convert.ToString(b, 10));//十进制 // Console.WriteLine(Convert.ToString(b, 16).ToUpper());//十六进制 //} //Console.ReadKey(); //将文件写入StreamTarget.txt using (Stream target = new FileStream(@"C:/Users/v-liuhch/Desktop/StreamTarget.txt", FileMode.Create, FileAccess.Write)) { target.Write(buffer, 0, buffer.Length); } source.Dispose(); #endregion
to split the reading of large files or It's more scientific, similar to the principle of uploading large files.