C# 通过物理路径将文件以二进制保存到指定文件夹

        /// <summary>
        /// 通过物理路径将文件以二进制保存到指定文件夹
        /// </summary>
        /// <param name="filePath">文件的物理路径</param>
        /// <param name="saveFilePath">需要保存的文件物理路径 + 文件后缀名</param>
        public string ReadFile(string filePath, string saveFilePath)
        {
            try
            {
                int byteLength = 0;
                //创建文件读取对象 
                using (FileStream fileReader = new FileStream(filePath, FileMode.Open))
                {
                    byteLength = (int)fileReader.Length;
                    //创建文件写入对象
                    using (FileStream fileWrite = new FileStream(saveFilePath, FileMode.Create))
                    {
                        //指定文件一次读取时的字节长度
                        byte[] by = new byte[1024 * 1024 * 10];
                        int count = 0;
                        while (true)
                        {
                            //将文件转换为二进制数据保存到内存中,同时返回读取字节的长度
                            count = fileReader.Read(by, 0, by.Length);
                            if (count == 0)//文件是否全部转换为二进制数据
                            {
                                break;
                            }
                            //将二进制数据转换为文件对象并保存到指定的物理路径中
                            fileWrite.Write(by, 0, count);
                        }
                        //MessageBox.Show("OK");
                    }
                }
                return Math.Round((double)byteLength / (1024 * 1024), 2).ToString() + "M";
            }
            catch (Exception ex)
            {
                return string.Empty;
                throw ex;
            }
        }

猜你喜欢

转载自www.cnblogs.com/yu-shang/p/11815585.html