C#文件转Byte存储到SQLServer数据库

场景:临时不同的系统,相同的数据库,通用文件读取

1.数据库

字段采用:varbinary(max)类型

2.代码

注:这里获取文件是通过先将byte[]数据先存到当前服务器对应项目的文件夹中(加了个判断是否存在该文件(已生成的就跳过),文件采用两个名字,一个是存进去的时间戳名字,一个是上传的名字(防止重复名字覆盖))

//保存
using (var fileStream = file.OpenReadStream())
                {
                    byte[] bytes = new byte[file.Length];
                    fileStream.Read(bytes, 0, (int)file.Length);
                    m.FileBytes = bytes;
                }
//获取文件
if (m.Id > 0)
            {
                var dPath = $"{_dirPath}/{m.TypeId}/{CurrentUserInfo.ID}/";
                var dPathUrl = $"{_dirPath_url}/{m.TypeId}/{CurrentUserInfo.ID}/";
                var dPathUrlFile = dPathUrl + m.TimestampName;
                if (!Directory.Exists(dPath))
                    Directory.CreateDirectory(dPath);
                if (!System.IO.File.Exists(dPathUrlFile) && m.FileBytes != null)//判断文件是否存在
                {
                    string filePath = Path.Combine(dPath, m.TimestampName);
                    FileStream fileStream = new FileStream(filePath, FileMode.Create);
                    fileStream.Write(m.FileBytes, 0, m.FileBytes.Length);
                    fileStream.Close();
                }
                return dPathUrlFile;
            }
            else
                return null;

 

感谢:http://www.manongjc.com/detail/12-wmsagmljhzvjfek.html

 

posted @ 2023-02-28 16:48  蜗牛的礼物  阅读(368)  评论(0编辑  收藏  举报