Home  >  Article  >  Backend Development  >  .net streams – file copying using streams

.net streams – file copying using streams

黄舟
黄舟Original
2017-02-24 10:44:081498browse

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;

First, use the stream for one-time copy and write

                                                           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 loop


In 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

PS: It is recommended to use;

to split the reading of large files or It's more scientific, similar to the principle of uploading large files.



# The above is the .net stream - using streams to process files Copied content, please pay attention to the PHP Chinese website (www.php.cn) for more related content!









##
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn