using System;
using System.Data;
using System.Configuration;
using System.IO;
using System.Web;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace BLL
{
/// <summary>
/// FileHelper 的摘要说明
/// </summary>
public static class FileHelper
{
/// <summary>
/// 返回指定目录的全部文件JSON序列化后的字符串
/// securityPath 为文件管理系统的目录,主要是为了截取FullName,这样返回到客户端的路径就看起来安全了
/// </summary>
/// <param name="cntDirectory">指定目录</param>
/// <param name="securityPath">安全路径过滤</param>
/// <param name="key">要搜索的文件名关键字</param>
/// <returns>全部文件JSON序列化后的字符串</returns>
public static string GetFiles(DirectoryInfo cntDirectory, string securityPath, string key)
{
//路径校正
securityPath = _JudgeDirectory(cntDirectory, securityPath);
FileInfo[] files;
//关键字搜索
if (string.IsNullOrEmpty(key))
files = cntDirectory.GetFiles();
else
files = cntDirectory.GetFiles(key);
List<FileEntity> fileList = new List<FileEntity>();
//填充至列表
foreach (FileInfo f in files)
{
fileList.Add(new FileEntity(f.Name, _CutFullName(f.FullName, securityPath), f.Length,
f.CreationTime, f.LastAccessTime,
f.LastWriteTime, f.Extension));
}
//返回
return Newtonsoft.Json.JavaScriptConvert.SerializeObject(fileList);
}
/// <summary>
/// 返回指定目录的全部文件JSON序列化后的字符串
/// securityPath 为文件管理系统的目录,主要是为了截取FullName,这样返回到客户端的路径就看起来安全了
/// </summary>
/// <param name="cntDirectory">指定目录</param>
/// <param name="securityPath">安全路径过滤</param>
/// <returns>全部文件JSON序列化后的字符串</returns>
public static string GetFiles(DirectoryInfo cntDirectory, string securityPath)
{
return GetFiles(cntDirectory, securityPath, string.Empty);
}
/// <summary>
/// 返回指定目录的全部子目录JSON序列化后的字符串
/// securityPath 为文件管理系统的目录,主要是为了截取FullName,这样返回到客户端的路径就看起来安全了
/// </summary>
/// <param name="cntDirectory">指定目录</param>
/// <param name="securityPath">安全路径过滤</param>
/// <returns>全部子目录JSON序列化后的字符串</returns>
public static string GetDirectories(DirectoryInfo cntDirectory, string securityPath)
{
//路径校正
securityPath = _JudgeDirectory(cntDirectory, securityPath);
DirectoryInfo[] dirs = cntDirectory.GetDirectories();
List<DirectoryEntity> dirList = new List<DirectoryEntity>();
//填充至列表
foreach (DirectoryInfo d in dirs)
{
dirList.Add(new DirectoryEntity(d.Name, _CutFullName(d.FullName, securityPath),
d.CreationTime, d.LastAccessTime,
d.LastWriteTime));
}
//返回
return Newtonsoft.Json.JavaScriptConvert.SerializeObject(dirList);
}
/// <summary>
/// 下载指定文件
/// </summary>
/// <param name="cntfile">带下载文件名</param>
/// <param name="securityPath">安全路径过滤</param>
/// <returns>下载成功与否</returns>
public static bool DownLoadFile(FileInfo cntfile, string securityPath)
{
//安全路径过滤
if (!_IsSecurityPath(cntfile.FullName, securityPath))
throw new Exception("不配允许的[securityPath]目录.");
//文件存在与否
if (!cntfile.Exists)
throw new FileNotFoundException();
return _ResponseFile(cntfile.Name, cntfile.FullName, 1024000);
}
/// <summary>
/// 删除指定的目录数组
/// </summary>
/// <param name="dirs"></param>
public static void DeleteDirectories(string[] dirs)
{
try
{
foreach (string dir in dirs)
{
if (!string.IsNullOrEmpty(dir))
{
if (Directory.Exists(dir))
Directory.Delete(dir, true);//删除子目录及相关文件
}
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 创建新的文件夹
/// </summary>
/// <param name="newdir"></param>
public static void CreateNewDirectory(string newdir)
{
try
{
Directory.CreateDirectory(newdir);
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 删除指定的文件数组
/// </summary>
/// <param name="dirs"></param>
public static void DeleteFiles(string[] files)
{
try
{
foreach (string file in files)
{
if (!string.IsNullOrEmpty(file))
{
if (File.Exists(file))
File.Delete(file);
}
}
}
catch (Exception ex)
{
throw ex;
}
}
#region 私有方法
/// <summary>
/// 对路径适当判断
/// 路径安全检测
/// 路径存在与否
/// 校正安全路径
/// </summary>
/// <param name="cntDirectory"></param>
/// <param name="securityPath"></param>
/// <returns></returns>
internal static string _JudgeDirectory(DirectoryInfo cntDirectory, string securityPath)
{
//安全路径过滤
if (!_IsSecurityPath(cntDirectory.FullName, securityPath))
throw new Exception("不配允许的[securityPath]目录.");
//存在与否
if (!cntDirectory.Exists)
throw new DirectoryNotFoundException();
//校正目录 去掉末尾的 /
securityPath = _AdjustPath(securityPath);
return securityPath;
}
/// <summary>
/// 截取文件或文件夹全名
/// </summary>
/// <param name="fullName"></param>
/// <param name="securityPath"></param>
/// <returns></returns>
internal static string _CutFullName(string fullName, string securityPath)
{
return fullName.Remove(0, securityPath.Length);
}
/// <summary>
/// 是否是被允许的安全路径
/// </summary>
/// <returns>是:真</returns>
internal static bool _IsSecurityPath(string path, string securityPath)
{
return path.IndexOf(securityPath) == -1 ? false : true;
}
/// <summary>
/// 校正路径,如果末尾有"/"就去掉
/// </summary>
/// <param name="string"></param>
/// <returns></returns>
internal static string _AdjustPath(string path)
{
if (string.IsNullOrEmpty(path))
return string.Empty;
else
{
return path.EndsWith(@"/") ? path.Remove(path.Length - 1) : path;
}
}
/// <summary>
///输出硬盘文件,提供下载 支持大文件、续传、速度限制、资源占用小
///调用例
///Page.Response.Clear();
///bool success = ResponseFile(Page.Request, Page.Response, "filename", @"C:/download.date", 1024000);
///if(!success)
/// Response.Write("下载文件出错!");
///Page.Response.End();
/// </summary>
/// <param name="_fileName">下载文件名</param>
/// <param name="_fullPath">带文件名下载路径</param>
/// <param name="_speed">每秒允许下载的字节数</param>
/// <returns>返回是否成功</returns>
internal static bool _ResponseFile(string _fileName, string _fullPath, long _speed)
{
try
{
HttpRequest _Request = HttpContext.Current.Request;
HttpResponse _Response = HttpContext.Current.Response;
FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader br = new BinaryReader(myFile);
try
{
_Response.AddHeader("Accept-Ranges", "bytes");
_Response.Buffer = false;
long fileLength = myFile.Length;
long startBytes = 0;
int pack = 10240; //10K bytes
//int sleep = 200; //每秒5次 即5*10K bytes每秒
int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1;
if (_Request.Headers["Range"] != null)
{
_Response.StatusCode = 206;
string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
startBytes = Convert.ToInt64(range[1]);
}
_Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
if (startBytes != 0)
{
_Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
}
_Response.AddHeader("Connection", "Keep-Alive");
_Response.ContentType = "application/octet-stream";
_Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));
br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;
for (int i = 0; i < maxCount; i++)
{
if (_Response.IsClientConnected)
{
_Response.BinaryWrite(br.ReadBytes(pack));
System.Threading.Thread.Sleep(sleep);
}
else
{
i = maxCount;
}
}
}
catch
{
return false;
}
finally
{
br.Close();
myFile.Close();
}
}
catch
{
return false;
}
return true;
}
#endregion
}
}