stream 文件操作

本文提供了一系列用于处理文件的实用方法,包括将流转换为字节数组、字节数组转换为流、读取文件为字节数组及将字节数组写入文件等。这些方法有助于简化文件读写过程。

简单的帮助类:

        private static byte[] StreamToBytes(Stream fs)
        {
            byte[] bArr = new byte[fs.Length];
            fs.Read(bArr, 0, (int)fs.Length);
            fs.Seek(0, SeekOrigin.Begin);
            return bArr;
        }

        public static Stream BytesToStream(byte[] bytes)
        {
            Stream stream = new MemoryStream(bytes);
            return stream;
        }


        public static byte[] FileToBytes(string path)
        {
            using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                byte[] bArr = new byte[fileStream.Length];
                fileStream.Read(bArr, 0, bArr.Length);
                return bArr;
            }
        }

        public static string BytesToFile(string directoryPath,byte[] bArr,string fileName)
        {
            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }
            string path = directoryPath + "\\" + fileName;
            using (FileStream fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
            {
                fileStream.Seek(0, SeekOrigin.Begin);
                fileStream.Write(bArr, 0, bArr.Length);
            }
            return path;
        }

 

转载于:https://www.cnblogs.com/lizejia/p/7505186.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值