将文件转换成二进制方法:
/// <summary>
/// 将文件转换成二进制
/// </summary>
/// <param name="Path">文件路径</param>
/// <returns></returns>
public static byte[] ConvertToBinary(string Path)
{
FileStream stream = new FileInfo(Path).OpenRead();
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, Convert.ToInt32(stream.Length));
return buffer;
}
将二进制转换成文件方法:
using System.IO;
string filePath = "D:\\a.jpg"; //文件路径
byte[] br = ConvertToBinary(filePath);
FileStream fstream = File.Create(filePath, br.Length);
try
{
fstream.Write(br, 0, br.Length); //二进制转换成文件
}
catch(Exception ex)
{
//抛出异常信息
}
finally
{
fstream.Close();
}
附加:二进制与图片互转
Image aa=newBitmap(@"E:\photo\tm.jpg");
System.IO.MemoryStream stream=newSystem.IO.MemoryStream();
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter=new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
formatter.Serialize(stream, aa);//将图像序列化成二进制流
stream.Position=0;
Image bb=(Image)formatter.Deserialize(stream); //将二进制流序列成Image
实际用法:目的:把jar包或者zip包(也可以过滤其他类型文件)保存到数据库里面。
private void UploadFile()
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "压缩文件|*.zip;*.jar";//文件扩展名(当然这里也可以过滤其他文件)
dialog.CheckFileExists = true;
dialog.ShowDialog();
if (!string.IsNullOrEmpty(dialog.FileName))//可以上传压缩包.zip 或者jar包
{
try
{
byte[] byteArray = FileBinaryConvertHelper.File2Bytes(dialog.FileName);//文件转成byte二进制数组
string JarContent = Convert.ToBase64String(byteArray);//将二进制转成string类型,可以存到数据库里面了
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
工具类:
/// <summary>
/// 工具类:文件与二进制流间的转换
/// </summary>
public class FileBinaryConvertHelper
{
/// <summary>
/// 将文件转换为byte数组
/// </summary>
/// <param name="path">文件地址</param>
/// <returns>转换后的byte数组</returns>
public static byte[] File2Bytes(string path)
{
if (!System.IO.File.Exists(path))
{
return new byte[0];
}
FileInfo fi = new FileInfo(path);
byte[] buff = new byte[fi.Length];
FileStream fs = fi.OpenRead();
fs.Read(buff, 0, Convert.ToInt32(fs.Length));
fs.Close();
return buff;
}
/// <summary>
/// 将byte数组转换为文件并保存到指定地址
/// </summary>
/// <param name="buff">byte数组</param>
/// <param name="savepath">保存地址</param>
public static void Bytes2File(byte[] buff, string savepath)
{
if (System.IO.File.Exists(savepath))
{
System.IO.File.Delete(savepath);
}
FileStream fs = new FileStream(savepath, FileMode.CreateNew);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(buff, 0, buff.Length);
bw.Close();
fs.Close();
}
}