文件与二进制操作小结
判断文件夹是否存在,不存在就创建
if (!Directory.Exists(ss))
{
Directory.CreateDirectory(ss);
}
判断文件是否存在,不存在就创建
if (!File.Exists(ss))
{
Directory.Create(ss);
}
保存一个二进制文件到磁盘指定路径
/// 保存一个二进制文件到磁盘指定路径
/// </summary>
/// <param name="path">磁盘路径</param>
/// <param name="bytes">二进制数据</param>
/// <returns></returns>
private void SaveFile(string path, byte[] bytes)
{
try
{
//若他们先将以二进制的形式存在于数据库中,则需要先读出来,然后将其转换为 byte
//byte[] bytes = (byte[])dr["content"];
System.IO.FileStream file = new System.IO.FileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.Write);
file.Write(bytes, 0, bytes.Length);
file.Close();
}
catch
{
throw;
}
}
/// <summary>
/// 读取文件并转换为二进制
/// </summary>
/// <param name="path">文件路径</param>
/// <returns>二进制数据</returns>
private static byte[] OpenFile(string path)
{
Byte[] byteSqlDate = null;
try
{
System.IO.FileStream file = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read);
byteSqlDate = new byte[file.Length];
file.Read(byteSqlDate, 0, byteSqlDate.Length);
file.Close();
}
catch
{
byteSqlDate = null;
}
return byteSqlDate;
}