当前位置:网站首页>[C # notes] use file stream to copy files

[C # notes] use file stream to copy files

2022-07-07 02:20:00 Start()

Namespace to be introduced : System.IO

C# A sealed copy of the file API:

System.IO.File.Copy(); // A copy of a document

System.IO.File.ReadAllBytes(); // Read all byte groups of the file

System.IO.File.WriteAllBytes(); // Write byte group to file

Next, I will do it myself , Use the way of reading and writing the file stream to copy the file , There are three main steps :

    public string filePath = @"C:\Users\Njiyue\Desktop\ddd.jpg";
    public string copyToPath = @"C:\Users\Njiyue\Desktop\ New folder \ccc.jpg";


    private void Test()
    {
    
        #region  First step :  obtain   Two files  “ flow ”
        FileInfo oneFileInfo = new FileInfo(filePath);
        if (!File.Exists(copyToPath))
            File.Create(copyToPath);// If there is no target file , Just create one 
        FileInfo twoFileInfo = new FileInfo(copyToPath);

        FileStream fs1 = oneFileInfo.OpenRead();// Read the file , Convert file to byte file 
        FileStream fs2 = twoFileInfo.OpenWrite();// write file , Convert file to byte file 
        #endregion


        #region  The second step :  Cyclic read write 
        byte[] buff = new byte[2048];// Read and write once 2048 Bytes 
        int contentLen = fs1.Read(buff, 0, 2048);// Read the file 2048 Bytes , And cache it to buff Byte group , Returns the read length , If the length is less than 2048, The description reads to the end , If it is equal to 0, It means that there are no bytes to read 
        // Loop read operation 
        while (contentLen != 0)
        {
    
            fs2.Write(buff, 0, contentLen); // Key method , Write the stream to 
            contentLen = fs1.Read(buff, 0, 2048);// Call once , Will be read in turn   next 2048 byte 
        }
        #endregion


        #region  The third step : Close the read-write process 
        // Turn off reading and writing , To avoid occupying files 
        fs1.Close();
        fs2.Close();
        fs1 = fs2 = null;
        #endregion
    }
原网站

版权声明
本文为[Start()]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130859204026.html