/// <para> FilesUpload:工具方法:ASP.NET上傳文件的方法</para>
/// <para> FileExists:返回文件是否存在</para>
/// <para> IsImgFilename:判斷文件名是否為瀏覽器可以直接顯示的圖片文件名</para>
/// <para> CopyFiles:復制指定目錄的所有文件</para>
/// <para> MoveFiles:移動指定目錄的所有文件</para>
/// <para> DeleteDirectoryFiles:刪除指定目錄的所有文件和子目錄</para>
/// <para> DeleteFiles:刪除指定目錄下的指定文件</para>
/// <para> CreateDirectory:創建指定目錄</para>
/// <para> CreateDirectory:建立子目錄</para>
/// <para> ReNameFloder:重命名文件夾</para>
/// <para> DeleteDirectory:刪除指定目錄</para>
/// <para> DirectoryIsExists:檢測目錄是否存在[+2方法重載]</para>
/// <para> DeleteSubDirectory:刪除指定目錄的所有子目錄,不包括對當前目錄文件的刪除</para>
/// <para> GetFileWriteTime:獲取文件最后修改時間</para>
/// <para> GetFileExtension:返回指定路徑的文件的擴展名</para>
/// <para> IsHiddenFile:判斷是否是隱藏文件</para>
/// <para> ReadTxtFile:以只讀方式讀取文本文件</para>
/// <para> WriteStrToTxtFile:將內容寫入文本文件(如果文件path存在就打開,不存在就新建)</para>
/// <para> GetLocalDrives:獲取本地驅動器名列表</para>
/// <para> GetAppCurrentDirectory:獲取應用程序當前可執行文件的路徑</para>
/// <para> GetFileSize:獲取文件大小並以B,KB,GB,TB方式表示[+2 重載]</para>
/// <para> DownLoadFiles:下載文件</para>
view sourceprint?
using System;
using System.Configuration;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.Security;
using System.IO;
using System.IO.Compression;
using System.Xml;
using System.Diagnostics;
using System.Windows.Forms;
using System.Threading;
namespace Utils
{
/// <summary>
/// <para> </para>
/// 常用工具類——文件操作類
/// <para> ---------------------------------------------------------------------------------------</para>
/// <para> FilesUpload:工具方法:ASP.NET上傳文件的方法</para>
/// <para> FileExists:返回文件是否存在</para>
/// <para> IsImgFilename:判斷文件名是否為瀏覽器可以直接顯示的圖片文件名</para>
/// <para> CopyFiles:復制指定目錄的所有文件</para>
/// <para> MoveFiles:移動指定目錄的所有文件</para>
/// <para> DeleteDirectoryFiles:刪除指定目錄的所有文件和子目錄</para>
/// <para> DeleteFiles:刪除指定目錄下的指定文件</para>
/// <para> CreateDirectory:創建指定目錄</para>
/// <para> CreateDirectory:建立子目錄</para>
/// <para> ReNameFloder:重命名文件夾</para>
/// <para> DeleteDirectory:刪除指定目錄</para>
/// <para> DirectoryIsExists:檢測目錄是否存在[+2方法重載]</para>
/// <para> DeleteSubDirectory:刪除指定目錄的所有子目錄,不包括對當前目錄文件的刪除</para>
/// <para> GetFileWriteTime:獲取文件最后修改時間</para>
/// <para> GetFileExtension:返回指定路徑的文件的擴展名</para>
/// <para> IsHiddenFile:判斷是否是隱藏文件</para>
/// <para> ReadTxtFile:以只讀方式讀取文本文件</para>
/// <para> WriteStrToTxtFile:將內容寫入文本文件(如果文件path存在就打開,不存在就新建)</para>
/// <para> GetLocalDrives:獲取本地驅動器名列表</para>
/// <para> GetAppCurrentDirectory:獲取應用程序當前可執行文件的路徑</para>
/// <para> GetFileSize:獲取文件大小並以B,KB,GB,TB方式表示[+2 重載]</para>
/// <para> DownLoadFiles:下載文件</para>
/// </summary>
public class FilesHelper
{
private const string PATH_SPLIT_CHAR = "\\";
#region 工具方法:ASP.NET上傳文件的方法
/// <summary>
/// 工具方法:上傳文件的方法
/// </summary>
/// <param name="myFileUpload">上傳控件的ID</param>
/// <param name="allowExtensions">允許上傳的擴展文件名類型,如:string[] allowExtensions = { ".doc", ".xls", ".ppt", ".jpg", ".gif" };</param>
/// <param name="maxLength">允許上傳的最大大小,以M為單位</param>
/// <param name="savePath">保存文件的目錄,注意是絕對路徑,如:Server.MapPath("~/upload/");</param>
/// <param name="saveName">保存的文件名,如果是""則以原文件名保存</param>
public static void FilesUpload(FileUpload myFileUpload, string[] allowExtensions, int maxLength, string savePath, string saveName)
{
// 文件格式是否允許上傳
bool fileAllow = false;
//檢查是否有文件案
if (myFileUpload.HasFile)
{
// 檢查文件大小, ContentLength獲取的是字節,轉成M的時候要除以2次1024
if (myFileUpload.PostedFile.ContentLength / 1024 / 1024 >= maxLength)
{
throw new Exception("只能上傳小於2M的文件!");
}
//取得上傳文件之擴展文件名,並轉換成小寫字母
string fileExtension = System.IO.Path.GetExtension(myFileUpload.FileName).ToLower();
string tmp = ""; // 存儲允許上傳的文件后綴名
//檢查擴展文件名是否符合限定類型
for (int i = 0; i < allowExtensions.Length; i++)
{
tmp += i == allowExtensions.Length - 1 ? allowExtensions[i] : allowExtensions[i] + ",";
if (fileExtension == allowExtensions[i])
{
fileAllow = true;
}
}
if (fileAllow)
{
try
{
string path = savePath + (saveName == "" ? myFileUpload.FileName : saveName);
//存儲文件到文件夾
myFileUpload.SaveAs(path);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
else
{
throw new Exception("文件格式不符,可以上傳的文件格式為:" + tmp);
}
}
else
{
throw new Exception("請選擇要上傳的文件!");
}
}
#endregion
#region 返回文件是否存在
/// <summary>
/// 返回文件是否存在
/// </summary>
/// <param name="filename">文件名</param>
/// <returns>是否存在</returns>
public static bool FileExists(string filename)
{
return System.IO.File.Exists(filename);
}
#endregion
#region 判斷文件名是否為瀏覽器可以直接顯示的圖片文件名
/// <summary>
/// 判斷文件名是否為瀏覽器可以直接顯示的圖片文件名
/// </summary>
/// <param name="filename">文件名</param>
/// <returns>是否可以直接顯示</returns>
public static bool IsImgFilename(string filename)
{
filename = filename.Trim();
if (filename.EndsWith(".") || filename.IndexOf(".") == -1)
{
return false;
}
string extname = filename.Substring(filename.LastIndexOf(".") + 1).ToLower();
return (extname == "jpg" || extname == "jpeg" || extname == "png" || extname == "bmp" || extname == "gif");
}
#endregion
#region 復制指定目錄的所有文件
/// <summary>
/// 復制指定目錄的所有文件
/// </summary>
/// <param name="sourceDir">原始目錄</param>
/// <param name="targetDir">目標目錄</param>
/// <param name="overWrite">如果為true,覆蓋同名文件,否則不覆蓋</param>
/// <param name="copySubDir">如果為true,包含目錄,否則不包含</param>
public static void CopyFiles(string sourceDir, string targetDir, bool overWrite, bool copySubDir)
{
//復制當前目錄文件
foreach (string sourceFileName in Directory.GetFiles(sourceDir))
{
string targetFileName = Path.Combine(targetDir, sourceFileName.Substring(sourceFileName.LastIndexOf(PATH_SPLIT_CHAR) + 1));
if (File.Exists(targetFileName))
{
if (overWrite == true)
{
File.SetAttributes(targetFileName, FileAttributes.Normal);
File.Copy(sourceFileName, targetFileName, overWrite);
}
}
else
{
File.Copy(sourceFileName, targetFileName, overWrite);
}
}
}
#endregion
#region 移動指定目錄的所有文件
/// <summary>
/// 移動指定目錄的所有文件
/// </summary>
/// <param name="sourceDir">原始目錄</param>
/// <param name="targetDir">目標目錄</param>
/// <param name="overWrite">如果為true,覆蓋同名文件,否則不覆蓋</param>
/// <param name="moveSubDir">如果為true,包含目錄,否則不包含</param>
public static void MoveFiles(string sourceDir, string targetDir, bool overWrite, bool moveSubDir)
{
//移動當前目錄文件
foreach (string sourceFileName in Directory.GetFiles(sourceDir))
{
string targetFileName = Path.Combine(targetDir, sourceFileName.Substring(sourceFileName.LastIndexOf(PATH_SPLIT_CHAR) + 1));
if (File.Exists(targetFileName))
{
if (overWrite == true)
{
File.SetAttributes(targetFileName, FileAttributes.Normal);
File.Delete(targetFileName);
File.Move(sourceFileName, targetFileName);
}
}
else
{
File.Move(sourceFileName, targetFileName);
}
}
if (moveSubDir)
{
foreach (string sourceSubDir in Directory.GetDirectories(sourceDir))
{
string targetSubDir = Path.Combine(targetDir, sourceSubDir.Substring(sourceSubDir.LastIndexOf(PATH_SPLIT_CHAR) + 1));
if (!Directory.Exists(targetSubDir))
Directory.CreateDirectory(targetSubDir);
MoveFiles(sourceSubDir, targetSubDir, overWrite, true);
Directory.Delete(sourceSubDir);
}
}
}
#endregion
#region 刪除指定目錄的所有文件和子目錄
/// <summary>
/// 刪除指定目錄的所有文件和子目錄
/// </summary>
/// <param name="TargetDir">操作目錄</param>
/// <param name="delSubDir">如果為true,包含對子目錄的操作</param>
public static void DeleteDirectoryFiles(string TargetDir, bool delSubDir)
{
foreach (string fileName in Directory.GetFiles(TargetDir))
{
File.SetAttributes(fileName, FileAttributes.Normal);
File.Delete(fileName);
}
if (delSubDir)
{
DirectoryInfo dir = new DirectoryInfo(TargetDir);
foreach (DirectoryInfo subDi in dir.GetDirectories())
{
DeleteDirectoryFiles(subDi.FullName, true);
subDi.Delete();
}
}
}
#endregion
#region 刪除指定目錄下的指定文件
/// <summary>
/// 刪除指定目錄下的指定文件
/// </summary>
/// <param name="TargetFileDir">指定文件的目錄</param>
public static void DeleteFiles(string TargetFileDir)
{
File.Delete(TargetFileDir);
}
#endregion
#region 創建指定目錄
/// <summary>
/// 創建指定目錄
/// </summary>
/// <param name="targetDir"></param>
public static void CreateDirectory(string targetDir)
{
DirectoryInfo dir = new DirectoryInfo(targetDir);
if (!dir.Exists)
dir.Create();
}
#endregion
#region 建立子目錄
/// <summary>
/// 建立子目錄
/// </summary>
/// <param name="parentDir">目錄路徑</param>
/// <param name="subDirName">子目錄名稱</param>
public static void CreateDirectory(string parentDir, string subDirName)
{
CreateDirectory(parentDir + PATH_SPLIT_CHAR + subDirName);
}
#endregion
#region 重命名文件夾
/// <summary>
/// 重命名文件夾
/// </summary>
/// <param name="OldFloderName">原路徑文件夾名稱</param>
/// <param name="NewFloderName">新路徑文件夾名稱</param>
/// <returns></returns>
public static bool ReNameFloder(string OldFloderName, string NewFloderName)
{
try
{
if (Directory.Exists(HttpContext.Current.Server.MapPath("//") + OldFloderName))
{
Directory.Move(HttpContext.Current.Server.MapPath("//") + OldFloderName, HttpContext.Current.Server.MapPath("//") + NewFloderName);
}
return true;
}
catch
{
return false;
}
}
#endregion
#region 刪除指定目錄
/// <summary>
/// 刪除指定目錄
/// </summary>
/// <param name="targetDir">目錄路徑</param>
public static void DeleteDirectory(string targetDir)
{
DirectoryInfo dirInfo = new DirectoryInfo(targetDir);
if (dirInfo.Exists)
{
DeleteDirectoryFiles(targetDir, true);
dirInfo.Delete(true);
}
}
#endregion
#region 檢測目錄是否存在
/// <summary>
/// 檢測目錄是否存在
/// </summary>
/// <param name="StrPath">路徑</param>
/// <returns></returns>
public static bool DirectoryIsExists(string StrPath)
{
DirectoryInfo dirInfo = new DirectoryInfo(StrPath);
return dirInfo.Exists;
}
/// <summary>
/// 檢測目錄是否存在
/// </summary>
/// <param name="StrPath">路徑</param>
/// <param name="Create">如果不存在,是否創建</param>
public static void DirectoryIsExists(string StrPath, bool Create)
{
DirectoryInfo dirInfo = new DirectoryInfo(StrPath);
//return dirInfo.Exists;
if (!dirInfo.Exists)
{
if (Create) dirInfo.Create();
}
}
#endregion
#region 刪除指定目錄的所有子目錄,不包括對當前目錄文件的刪除
/// <summary>
/// 刪除指定目錄的所有子目錄,不包括對當前目錄文件的刪除
/// </summary>
/// <param name="targetDir">目錄路徑</param>
public static void DeleteSubDirectory(string targetDir)
{
foreach (string subDir in Directory.GetDirectories(targetDir))
{
DeleteDirectory(subDir);
}
}
#endregion
#region 獲取文件最后修改時間
/// <summary>
/// 獲取文件最后修改時間
/// </summary>
/// <param name="FileUrl">文件真實路徑</param>
/// <returns></returns>
public DateTime GetFileWriteTime(string FileUrl)
{
return File.GetLastWriteTime(FileUrl);
}
#endregion
#region 返回指定路徑的文件的擴展名
/// <summary>
/// 返回指定路徑的文件的擴展名
/// </summary>
/// <param name="PathFileName">完整路徑的文件</param>
/// <returns></returns>
public string GetFileExtension(string PathFileName)
{
return Path.GetExtension(PathFileName);
}
#endregion
#region 判斷是否是隱藏文件
/// <summary>
/// 判斷是否是隱藏文件
/// </summary>
/// <param name="path">文件路徑</param>
/// <returns></returns>
public bool IsHiddenFile(string path)
{
FileAttributes MyAttributes = File.GetAttributes(path);
string MyFileType = MyAttributes.ToString();
if (MyFileType.LastIndexOf("Hidden") != -1) //是否隱藏文件
{
return true;
}
else
return false;
}
#endregion
#region 以只讀方式讀取文本文件
/// <summary>
/// 以只讀方式讀取文本文件
/// </summary>
/// <param name="FilePath">文件路徑及文件名</param>
/// <returns></returns>
public static string ReadTxtFile(string FilePath)
{
string content = "";//返回的字符串
using (FileStream fs = new FileStream(FilePath, FileMode.Open))
{
using (StreamReader reader = new StreamReader(fs, Encoding.UTF8))
{
string text = string.Empty;
while (!reader.EndOfStream)
{
text += reader.ReadLine() + "\r\n";
content = text;
}
}
}
return content;
}
#endregion
#region 將內容寫入文本文件(如果文件path存在就打開,不存在就新建)
/// <summary>
/// 將內容寫入文本文件(如果文件path存在就打開,不存在就新建)
/// </summary>
/// <param name="FilePath">文件路徑</param>
/// <param name="WriteStr">要寫入的內容</param>
/// <param name="FileModes">寫入模式:append 是追加寫, CreateNew 是覆蓋</param>
public static void WriteStrToTxtFile(string FilePath, string WriteStr, FileMode FileModes)
{
FileStream fst = new FileStream(FilePath, FileModes);
StreamWriter swt = new StreamWriter(fst, System.Text.Encoding.GetEncoding("utf-8"));
swt.WriteLine(WriteStr);
swt.Close();
fst.Close();
}
#endregion
#region 獲取本地驅動器名列表
/// <summary>
/// 獲取本地驅動器名列表
/// </summary>
/// <returns></returns>
public static string[] GetLocalDrives()
{
return Directory.GetLogicalDrives();
}
#endregion
#region 獲取應用程序當前可執行文件的路徑
/// <summary>
/// 獲取應用程序當前可執行文件的路徑
/// </summary>
/// <returns></returns>
public static string GetAppCurrentDirectory()
{
return Application.StartupPath;
}
#endregion
#region 獲取文件大小並以B,KB,GB,TB方式表示[+2 重載]
/// <summary>
/// 獲取文件大小並以B,KB,GB,TB方式表示
/// </summary>
/// <param name="File">文件(FileInfo類型)</param>
/// <returns></returns>
public static string GetFileSize(FileInfo File)
{
string Result = "";
long FileSize = File.Length;
if (FileSize >= 1024 * 1024 * 1024)
{
if (FileSize / 1024 * 1024 * 1024 * 1024 >= 1024) Result = string.Format("{0:############0.00} TB", (double)FileSize / 1024 * 1024 * 1024 * 1024);
else Result = string.Format("{0:####0.00} GB", (double)FileSize / 1024 * 1024 * 1024);
}
else if (FileSize >= 1024 * 1024) Result = string.Format("{0:####0.00} MB", (double)FileSize / 1024 * 1024);
else if (FileSize >= 1024) Result = string.Format("{0:####0.00} KB", (double)FileSize / 1024);
else Result = string.Format("{0:####0.00} Bytes", FileSize);
return Result;
}
/// <summary>
/// 獲取文件大小並以B,KB,GB,TB方式表示
/// </summary>
/// <param name="FilePath">文件的具體路徑</param>
/// <returns></returns>
public static string GetFileSize(string FilePath)
{
string Result = "";
FileInfo File = new FileInfo(FilePath);
long FileSize = File.Length;
if (FileSize >= 1024 * 1024 * 1024)
{
if (FileSize / 1024 * 1024 * 1024 * 1024 >= 1024) Result = string.Format("{0:########0.00} TB", (double)FileSize / 1024 * 1024 * 1024 * 1024);
else Result = string.Format("{0:####0.00} GB", (double)FileSize / 1024 * 1024 * 1024);
}
else if (FileSize >= 1024 * 1024) Result = string.Format("{0:####0.00} MB", (double)FileSize / 1024 * 1024);
else if (FileSize >= 1024) Result = string.Format("{0:####0.00} KB", (double)FileSize / 1024);
else Result = string.Format("{0:####0.00} Bytes", FileSize);
return Result;
}
#endregion
#region 下載文件
/// <summary>
/// 下載文件
/// </summary>
/// <param name="FileFullPath">下載文件下載的完整路徑及名稱</param>
public static void DownLoadFiles(string FileFullPath)
{
if (!string.IsNullOrEmpty(FileFullPath) && FileExists(FileFullPath))
{
FileInfo fi = new FileInfo(FileFullPath);//文件信息
FileFullPath = HttpUtility.UrlEncode(FileFullPath); //對文件名編碼
FileFullPath = FileFullPath.Replace("+", "%20"); //解決空格被編碼為"+"號的問題
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileFullPath);
HttpContext.Current.Response.AppendHeader("content-length", fi.Length.ToString()); //文件長度
int chunkSize = 102400;//緩存區大小,可根據服務器性能及網絡情況進行修改
byte[] buffer = new byte[chunkSize]; //緩存區
using (FileStream fs = fi.Open(FileMode.Open)) //打開一個文件流
{
while (fs.Position >= 0 && HttpContext.Current.Response.IsClientConnected) //如果沒到文件尾並且客戶在線
{
int tmp = fs.Read(buffer, 0, chunkSize);//讀取一塊文件
if (tmp <= 0) break; //tmp=0說明文件已經讀取完畢,則跳出循環
HttpContext.Current.Response.OutputStream.Write(buffer, 0, tmp);//向客戶端傳送一塊文件
HttpContext.Current.Response.Flush();//保證緩存全部送出
Thread.Sleep(10);//主線程休息一下,以釋放CPU
}
}
}
}
#endregion
}
}