public class FileHelper
{
#region " [Contants]"
/// <summary>
/// 要保存的类型
/// </summary>
public enum SaveType
{
/// <summary>
/// 导入文件的保存目录
/// </summary>
Import = 1,
/// <summary>
/// 导出文件的保存目录
/// </summary>
Export = 2,
/// <summary>
/// 上传服务合同
/// </summary>
UploadServiceContract=3,
}
#endregion
/// <summary>
/// 将文件上传到指定位置
/// </summary>
/// <param name="file">上传控件</param>
/// /// <param name="fileName">指定的文件名,如果设置fileName="",则根据上传的文件名自动生成新的文件名</param>
/// <param name="type">保存类型</param>
/// <param name="strFormat">允许上传的格式</param>
/// <returns>文件最后的保存路径</returns>
public static string UploadFile(FileUpload file, string fileName, SaveType type,string strFormat)
{
if (!file.HasFile)
{
throw new NullReferenceException("请选择文件!");
}
if(!WebHelper.IsFormat(file.PostedFile.FileName,strFormat))
{
throw new FormatException(string.Format("格式错误,允许上传的格式为 {0}",strFormat));
}
string strDirectory = "";
switch (type)
{
case SaveType.Export:
strDirectory = HttpContext.Current.Server.MapPath(WebHelper.ExportPath);
break;
case SaveType.Import:
strDirectory = HttpContext.Current.Server.MapPath(WebHelper.ImportPath);
break;
case SaveType.UploadServiceContract:
strDirectory = HttpContext.Current.Server.MapPath(WebHelper.ServiceContractFileUploadPath);
break;
}
if (string.IsNullOrEmpty(strDirectory))
{
throw new ApplicationException("初始化错误,请配置文件的保存目录...");
}
//判断目录是否存在,不存在就创建
CreateDirectory(strDirectory);
//生成文件名称,如果传递进来的参数fileName="",则根据上传的文件名自动生成新的文件名
string strFileName = string.IsNullOrEmpty(fileName) ? GenerateFileName(file.FileName, GetFileExtension(file.PostedFile.FileName)) : fileName;
//最终的保存路径
string strSavePath = string.Format("{0}\\{1}", strDirectory, strFileName);
file.SaveAs(strSavePath);
return strSavePath;
}
/// <summary>
/// 下载文件
/// </summary>
/// <param name="fileName">文件名</param>
/// <param name="filePath">文件的保存目录</param>
/// <param name="isRemoveSource">是否删除源文件</param>
/// <param name="isEndResponse">页面的请求是否完成。
/// 1. 在 try {} catch 中调用本方法时,需设置 isEndResponse=false,然后在 finally 中显式调用Response.End(); (参考页面:SSMP/Maintain/MaintainOneAngles.aspx)
/// 2. 当调用本方法后还需要继续执行操作,也需设置 isEndResponse=false,然后在操作的最后调用 Response.End(); (参考页面:SSMP/FileInfoManage/FileInfoList.aspx)
/// 3. 当一个事件执行下载操作之后,不需要在执行其他的操作,并且该方法的调用不在 try {} catch 里时,才设置 isEndResponse=true</param>
///=============================================================================================
/// <returns></returns>
public static bool DownLoadFile(string fileName, string filePath, bool isRemoveSource, bool isEndResponse)
{
if (File.Exists(filePath))
{
FileInfo file = new FileInfo(filePath);
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); //解决中文乱码
string fileExtension = System.IO.Path.GetExtension(System.IO.Path.GetFileName(filePath));//文件扩展名
if (HttpContext.Current.Request.UserAgent.ToLower().IndexOf("msie") > -1)
{
//当客户端使用IE时,对其进行编码;使用 ToHexString 代替传统的 UrlEncode();
fileName = ToHexString(fileName);
}
if (HttpContext.Current.Request.UserAgent.ToLower().IndexOf("firefox") > -1)
{
//为了向客户端输出空格,需要在当客户端使用 Firefox 时特殊处理
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
}
else
{
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
}
HttpContext.Current.Response.AddHeader("Content-length", file.Length.ToString());
HttpContext.Current.Response.ContentType = "appliction/octet-stream";
HttpContext.Current.Response.WriteFile(file.FullName);
HttpContext.Current.Response.Flush();
if (isRemoveSource)
{
RemoveFile(filePath);
}
if (isEndResponse)
{
HttpContext.Current.Response.End();
}
else
{
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
return true;
}
else
{
return false;
}
}
/// <summary>
/// 默认的根据时间格式生成文件名称
/// </summary>
/// <param name="fileName">文件名</param>
/// <param name="fileExtension">文件后缀</param>
/// <returns></returns>
public static string GenerateFileName(string fileName, string fileExtension)
{
string strPrefix = fileName;
if (fileName.IndexOf('.') > 0)
{
strPrefix = fileName.Remove(fileName.LastIndexOf('.'));
}
return string.Format("{0}{1}{2}", strPrefix, DateTime.Now.ToString("yyyyMMddhhmmss"), fileExtension);
}
/// <summary>
/// 检测文件目录是否存在,如果不存在则创建
/// </summary>
/// <param name="strDirectory"></param>
public static void CreateDirectory(string strDirectory)
{
if (Directory.Exists(strDirectory))
{
return;
}
Directory.CreateDirectory(strDirectory);
}
public static void RemoveFile(string strFilePath)
{
FileInfo file = new FileInfo(strFilePath);
if (file.Exists)
{
file.Delete();
}
}
public static string GetFileName(string strFullPath)
{
if (string.IsNullOrEmpty(strFullPath))
return string.Empty;
return Path.GetFileName(strFullPath);
}
public static string GetFileExtension(string strFullPath)
{
if (string.IsNullOrEmpty(strFullPath))
return string.Empty;
return Path.GetExtension(strFullPath);
}
public static bool IsExists(string strFilePath)
{
try
{
FileInfo file = new FileInfo(strFilePath);
return file.Exists;
}
catch (Exception ex)
{
return false;
}
}
#region " [编码]"
/// <summary>
/// 对字符串中的非 ASCII 字符进行编码
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string ToHexString(string s)
{
char[] chars = s.ToCharArray();
StringBuilder builder = new StringBuilder();
for (int index = 0; index < chars.Length; index++)
{
bool needToEncode = NeedToEncode(chars[index]);
if (needToEncode)
{
string encodedString = ToHexString(chars[index]);
builder.Append(encodedString);
}
else
{
builder.Append(chars[index]);
}
}
return builder.ToString();
}
/// <summary>
/// 判断字符是否需要使用特殊的 ToHexString 的编码方式
/// </summary>
/// <param name="chr"></param>
/// <returns></returns>
private static bool NeedToEncode(char chr)
{
string reservedChars = "$-_.+!*'(),@=&";
if (chr > 127)
return true;
if (char.IsLetterOrDigit(chr) || reservedChars.IndexOf(chr) >= 0)
return false;
return true;
}
/// <summary>
/// 为非 ASCII 字符编码
/// </summary>
/// <param name="chr"></param>
/// <returns></returns>
private static string ToHexString(char chr)
{
UTF8Encoding utf8 = new UTF8Encoding();
byte[] encodedBytes = utf8.GetBytes(chr.ToString());
StringBuilder builder = new StringBuilder();
for (int index = 0; index < encodedBytes.Length; index++)
{
builder.AppendFormat("%{0}", Convert.ToString(encodedBytes[index], 16));
}
return builder.ToString();
}
#endregion
#region 杀掉所有 winword.exe 进程
/// <summary>
/// 创建人:郑小平
/// 创建日期:2011-07-26
/// 功能:杀掉所有 winword.exe 进程
///===================================
/// </summary>
public static void KillWordProcess()
{
System.Diagnostics.Process[] myPs;
myPs = System.Diagnostics.Process.GetProcesses();
foreach (System.Diagnostics.Process p in myPs)
{
if (p.Id != 0)
{
string myS = "WINWORD.EXE" + p.ProcessName + "ID;" + p.Id.ToString();
try
{
if (p.Modules != null)
if (p.Modules.Count > 0)
{
System.Diagnostics.ProcessModule pm = p.Modules[0];
myS += "\n Modules[0].FileName;" + pm.FileName;
myS += "\n Modules[0].ModuleName;" + pm.ModuleName;
myS += "\n Modules[0].FileVersionInfo;\n" + pm.FileVersionInfo.ToString();
if (pm.ModuleName.ToLower() == "winword.exe")
p.Kill();
}
}
catch
{
}
}
}
}
#endregion
}