FileStream文件合并

简要:

模拟windows命令行(CMD)进行文件合并的功能,使用FileStream对文件进行字节的读取,实现多个文件合并成一个新的文件。

练习作用:使用FileStream操作文件流进行读取。

程序效果图:

实现代码:

 class Program
    {
        static void Main(string[] args)
        {

            //参数获取
            string command = args[0];
            string command_sub = args[1];                 

            string[] sourceFiles =  args[2].Split('+'); //所有需要合并的文件名
            string fileNew = args[args.Length - 1]; //合并后的文件名

            //命令效验
            if (command!="copy"&&command_sub.ToLower()!="/b")
            {
                return;
            }

            FilesCombine(sourceFiles, fileNew);

            Console.WriteLine("OK");

        } // main

        static void FilesCombine(string [] sourceFilePaths, string outputFilePath)
        {
            Stream fsWrite = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write);

            //遍历所有合并文件 (即读即写)
            for (int i = 0; i < sourceFilePaths.Length; i++)
            {
                string fileName = sourceFilePaths[i];
                //读取文件流
                Stream fsRead = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                int n = 0;
                while ((n = fsRead.ReadByte()) != -1)
                {
                    fsWrite.WriteByte((byte)n);
                }
                fsRead.Dispose(); //每读完一个文件释放文件流资源

            }

            fsWrite.Dispose();

        }  // END FileWtiteToStream()

    }
原文地址:https://www.cnblogs.com/green-jcx/p/13157090.html