0
点赞
收藏
分享

微信扫一扫

C#文件转byte[]再将byte[]转文件


将文件转为byte[]然后再将byte[]转成文件,这本是没什么难度的事,可是很多人在做将文件转为byte[]时很容易忽略 ​​fs.Read(buffur, 0, (int)buffur.Length);​​ 语句导致byte[]变量中的信息为空,然后拿着这个没有信息的变量将其转换成文件结果可想而知,文件为空无法使用。在这作为一个记录,也算是给自己一个警示。

namespace PDFtoByte
{
internal class Program
{
static void Main(string[] args)
{
var byteArray = FileToByteArray(@"C:\Users\Administrator\Desktop\CreatePDF\入院病人信息表.pdf");
ByteToPDF(byteArray);
}

/// <summary>
/// 文件 转 Byte[]
/// </summary>
/// <param name="fileUrl"></param>
/// <returns></returns>
static byte[] FileToByteArray(string fileUrl)
{
using (FileStream fs = new(fileUrl, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
{
byte[] buffur = new byte[fs.Length];
// 注意:一定要读取否则。。。值得一试😂
fs.Read(buffur, 0, (int)buffur.Length);
return buffur;
}
}

/// <summary>
/// Byte[] 转 File
/// </summary>
/// <param name="fileData"></param>
static void ByteToFile(byte[] fileData)
{
string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".pdf";
string dirPath = @"C:\Users\Administrator\Desktop\CreatePDF";

if (!Directory.Exists(dirPath))
Directory.CreateDirectory(dirPath);

string filePath = Path.Combine(dirPath, fileName);
FileStream fileStream = new(filePath, FileMode.Create);
fileStream.Write(fileData, 0, fileData.Length);
fileStream.Close();
}
}
}


举报

相关推荐

0 条评论