天天看点

分割文件与合并文件

int splitFileSize = 1 * 1024 * 1024;

        /// <summary>
        ///
        /// </summary>
        /// <param name="fileName"></param>
        public List<string> SplitFile(string fileName)
        {
            List<string> list = new List<string>();
            FileInfo f = new FileInfo(fileName);
            if (f.Length <= splitFileSize)
            {
                list.Add(fileName);
            }
            else
            {
                string path = Path.GetDirectoryName(fileName);
                string fname = Path.GetFileNameWithoutExtension(fileName);
                string tmpPath = string.Format(@"{0}\tmp_{1}", path, fname);
                if (Directory.Exists(tmpPath))
                {
                    Directory.Delete(tmpPath, true);
                }
                Directory.CreateDirectory(tmpPath);
                using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    using (BinaryReader br = new BinaryReader(fs))
                    {
                        int couter = 1;
                        bool isReadingComplete = false;
                        while (!isReadingComplete)
                        {
                            string fpath = string.Format(@"{0}\{1}", tmpPath, couter);
                            list.Add(fpath);
                            byte[] input = br.ReadBytes(splitFileSize);
                            using (FileStream fw = new FileStream(fpath, FileMode.Create))
                            {
                                using (BinaryWriter bw = new BinaryWriter(fw))
                                {
                                    bw.Write(input);
                                }
                            }

                            isReadingComplete = (input.Length != splitFileSize);
                            if (!isReadingComplete)
                            {
                                couter += 1;
                            }
                        }
                    }
                }
            }
            return      
public void MergeFile(string partPath, int maxName, string fileName)
        {
            using (FileStream fw = new FileStream(fileName, FileMode.Create))
            {
                using (BinaryWriter bw = new BinaryWriter(fw))
                {
                    for (int i = 1; i <= maxName; i++)
                    {
                        string fname = string.Format(@"{0}\{1}", partPath, i);

                        using (Stream sr = new FileStream(fname, FileMode.Open))
                        {
                            using (BinaryReader br = new BinaryReader(sr))
                            {
                                bw.Write(br.ReadBytes((int)sr.Length));
                            }
                        }
                    }
                }
            }
        }