123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796 |
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.IO;
- using System.Net;
- using System.Text;
- namespace TEAMModelOS.SDK.Helper.Common.FileHelper
- {
- public class FileHelper
- {
- #region 获取文件到集合中
- /// <summary>
- /// 读取指定位置文件列表到集合中
- /// </summary>
- /// <param name="path">指定路径</param>
- /// <returns></returns>
- public static DataTable GetFileTable(string path)
- {
- DataTable dt = new DataTable();
- dt.Columns.Add("name", typeof(string));
- dt.Columns.Add("ext", typeof(string));
- dt.Columns.Add("size", typeof(long));
- dt.Columns.Add("time", typeof(DateTime));
- DirectoryInfo dirinfo = new DirectoryInfo(path);
- FileInfo fi;
- DirectoryInfo dir;
- string FileName, FileExt;
- long FileSize = 0;
- DateTime FileModify;
- try
- {
- foreach (FileSystemInfo fsi in dirinfo.GetFileSystemInfos())
- {
- FileName = string.Empty;
- FileExt = string.Empty;
- if (fsi is FileInfo)
- {
- fi = (FileInfo)fsi;
- //获取文件名称
- FileName = fi.Name;
- //获取文件扩展名
- FileExt = fi.Extension;
- //获取文件大小
- FileSize = fi.Length;
- //获取文件最后修改时间
- FileModify = fi.LastWriteTime;
- }
- else
- {
- dir = (DirectoryInfo)fsi;
- //获取目录名
- FileName = dir.Name;
- //获取目录最后修改时间
- FileModify = dir.LastWriteTime;
- //设置目录文件为文件夹
- FileExt = "文件夹";
- }
- DataRow dr = dt.NewRow();
- dr["name"] = FileName;
- dr["ext"] = FileExt;
- dr["size"] = FileSize;
- dr["time"] = FileModify;
- dt.Rows.Add(dr);
- }
- }
- catch
- {
- throw;
- }
- return dt;
- }
- #endregion
- #region 检测指定路径是否存在
- /// <summary>
- /// 检测指定路径是否存在
- /// </summary>
- /// <param name="path">目录的绝对路径</param>
- public static bool IsExistDirectory(string path)
- {
- return Directory.Exists(path);
- }
- #endregion
- #region 检测指定文件是否存在,如果存在则返回true
- /// <summary>
- /// 检测指定文件是否存在,如果存在则返回true
- /// </summary>
- /// <param name="filePath">文件的绝对路径</param>
- public static bool IsExistFile(string filePath)
- {
- return File.Exists(filePath);
- }
- #endregion
- #region 创建文件夹
- /// <summary>
- /// 创建文件夹
- /// </summary>
- /// <param name="folderPath">文件夹的绝对路径</param>
- public static void CreateFolder(string folderPath)
- {
- if (!IsExistDirectory(folderPath))
- {
- Directory.CreateDirectory(folderPath);
- }
- }
- #endregion
- #region 判断上传文件后缀名
- /// <summary>
- /// 判断上传文件后缀名
- /// </summary>
- /// <param name="strExtension">后缀名</param>
- public static bool IsCanEdit(string strExtension)
- {
- strExtension = strExtension.ToLower();
- if (strExtension.LastIndexOf(".", StringComparison.Ordinal) >= 0)
- {
- strExtension = strExtension.Substring(strExtension.LastIndexOf(".", StringComparison.Ordinal));
- }
- else
- {
- strExtension = ".txt";
- }
- string[] strArray = new string[] { ".htm", ".html", ".txt", ".js", ".css", ".xml", ".sitemap" };
- for (int i = 0; i < strArray.Length; i++)
- {
- if (strExtension.Equals(strArray[i]))
- {
- return true;
- }
- }
- return false;
- }
- public static bool IsSafeName(string strExtension)
- {
- strExtension = strExtension.ToLower();
- if (strExtension.LastIndexOf(".") >= 0)
- {
- strExtension = strExtension.Substring(strExtension.LastIndexOf("."));
- }
- else
- {
- strExtension = ".txt";
- }
- string[] strArray = new string[] { ".jpg", ".gif", ".png" };
- for (int i = 0; i < strArray.Length; i++)
- {
- if (strExtension.Equals(strArray[i]))
- {
- return true;
- }
- }
- return false;
- }
- public static bool IsZipName(string strExtension)
- {
- strExtension = strExtension.ToLower();
- if (strExtension.LastIndexOf(".") >= 0)
- {
- strExtension = strExtension.Substring(strExtension.LastIndexOf("."));
- }
- else
- {
- strExtension = ".txt";
- }
- string[] strArray = new string[] { ".zip", ".rar" };
- for (int i = 0; i < strArray.Length; i++)
- {
- if (strExtension.Equals(strArray[i]))
- {
- return true;
- }
- }
- return false;
- }
- #endregion
- #region 创建文件夹
- /// <summary>
- /// 创建文件夹
- /// </summary>
- /// <param name="fileName">文件的绝对路径</param>
- public static void CreateSuffic(string fileName)
- {
- try
- {
- if (!Directory.Exists(fileName))
- {
- Directory.CreateDirectory(fileName);
- }
- }
- catch (Exception ex)
- {
- var s = ex.Message;
- throw;
- }
- }
- /// <summary>
- /// 创建文件夹
- /// </summary>
- /// <param name="fileName">文件的绝对路径</param>
- public static void CreateFiles(string fileName)
- {
- try
- {
- //判断文件是否存在,不存在创建该文件
- if (!IsExistFile(fileName))
- {
- FileInfo file = new FileInfo(fileName);
- FileStream fs = file.Create();
- fs.Close();
- }
- }
- catch { throw; }
- }
- /// <summary>
- /// 创建一个文件,并将字节流写入文件。
- /// </summary>
- /// <param name="filePath">文件的绝对路径</param>
- /// <param name="buffer">二进制流数据</param>
- public static void CreateFile(string filePath, byte[] buffer)
- {
- try
- {
- //判断文件是否存在,不存在创建该文件
- if (!IsExistFile(filePath))
- {
- FileInfo file = new FileInfo(filePath);
- FileStream fs = file.Create();
- fs.Write(buffer, 0, buffer.Length);
- fs.Close();
- }
- else
- {
- File.WriteAllBytes(filePath, buffer);
- }
- }
- catch { throw; }
- }
- #endregion
- #region 将文件移动到指定目录
- /// <summary>
- /// 将文件移动到指定目录
- /// </summary>
- /// <param name="sourceFilePath">需要移动的源文件的绝对路径</param>
- /// <param name="descDirectoryPath">移动到的目录的绝对路径</param>
- public static void Move(string sourceFilePath, string descDirectoryPath)
- {
- string sourceName = GetFileName(sourceFilePath);
- if (IsExistDirectory(descDirectoryPath))
- {
- //如果目标中存在同名文件,则删除
- if (IsExistFile(descDirectoryPath + "\\" + sourceFilePath))
- {
- DeleteFile(descDirectoryPath + "\\" + sourceFilePath);
- }
- else
- {
- //将文件移动到指定目录
- File.Move(sourceFilePath, descDirectoryPath + "\\" + sourceName);
- }
- }
- }
- #endregion
- # region 将源文件的内容复制到目标文件中
- /// <summary>
- /// 将源文件的内容复制到目标文件中
- /// </summary>
- /// <param name="sourceFilePath">源文件的绝对路径</param>
- /// <param name="descDirectoryPath">目标文件的绝对路径</param>
- public static void Copy(string sourceFilePath, string descDirectoryPath)
- {
- File.Copy(sourceFilePath, descDirectoryPath, true);
- }
- #endregion
- #region 从文件的绝对路径中获取文件名( 不包含扩展名 )
- /// <summary>
- /// 从文件的绝对路径中获取文件名( 不包含扩展名 )
- /// </summary>
- /// <param name="filePath">文件的绝对路径</param>
- public static string GetFileName(string filePath)
- {
- FileInfo file = new FileInfo(filePath);
- return file.Name;
- }
- #endregion
- #region 获取文件的后缀名
- /// <summary>
- /// 获取文件的后缀名
- /// </summary>
- /// <param name="filePath">文件的绝对路径</param>
- public static string GetExtension(string filePath)
- {
- FileInfo file = new FileInfo(filePath);
- return file.Extension;
- }
- /// <summary>
- /// 返回文件扩展名,不含“.”
- /// </summary>
- /// <param name="filepath">文件全名称</param>
- /// <returns>string</returns>
- public static string GetFileExt(string filepath)
- {
- if (string.IsNullOrEmpty(filepath))
- {
- return "";
- }
- if (filepath.LastIndexOf(".", StringComparison.Ordinal) > 0)
- {
- return filepath.Substring(filepath.LastIndexOf(".", StringComparison.Ordinal) + 1); //文件扩展名,不含“.”
- }
- return "";
- }
- #endregion
- #region 删除指定文件
- /// <summary>
- /// 删除指定文件
- /// </summary>
- /// <param name="filePath">文件的绝对路径</param>
- public static void DeleteFile(string filePath)
- {
- if (IsExistFile(filePath))
- {
- File.Delete(filePath);
- }
- }
- #endregion
- // <summary>
- ///直接删除指定目录下的所有文件及文件夹(保留目录)
- /// </summary>
- /// <param name="strPath">文件夹路径</param>
- /// <returns>执行结果</returns>
- public static void DeleteDirAndFiles(string file)
- {
- try
- {
- //去除文件夹和子文件的只读属性
- //去除文件夹的只读属性
- System.IO.DirectoryInfo fileInfo = new DirectoryInfo(file);
- fileInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;
- //去除文件的只读属性
- System.IO.File.SetAttributes(file, System.IO.FileAttributes.Normal);
- //判断文件夹是否还存在
- if (Directory.Exists(file))
- {
- foreach (string f in Directory.GetFileSystemEntries(file))
- {
- if (File.Exists(f))
- {
- //如果有子文件删除文件
- File.Delete(f);
- }
- else
- {
- //循环递归删除子文件夹
- DeleteDirAndFiles(f);
- }
- }
- //删除空文件夹
- Directory.Delete(file);
- }
- }
- catch (Exception ex) // 异常处理
- {
- }
- }
- #region 删除指定目录及其所有子目录
- /// <summary>
- /// 删除指定目录及其所有子目录
- /// </summary>
- /// <param name="directoryPath">文件的绝对路径</param>
- public static void DeleteDirectory(string directoryPath)
- {
- if (IsExistDirectory(directoryPath))
- {
- Directory.Delete(directoryPath);
- }
- }
- #endregion
- #region 清空指定目录下所有文件及子目录,但该目录依然保存.
- /// <summary>
- /// 清空指定目录下所有文件及子目录,但该目录依然保存.
- /// </summary>
- /// <param name="directoryPath">指定目录的绝对路径</param>
- public static void ClearDirectory(string directoryPath)
- {
- if (!IsExistDirectory(directoryPath)) return;
- //删除目录中所有的文件
- string[] fileNames = GetFileNames(directoryPath);
- for (int i = 0; i < fileNames.Length; i++)
- {
- DeleteFile(fileNames[i]);
- }
- //删除目录中所有的子目录
- string[] directoryNames = GetDirectories(directoryPath);
- for (int i = 0; i < directoryNames.Length; i++)
- {
- DeleteDirectory(directoryNames[i]);
- }
- }
- #endregion
- #region 剪切 粘贴
- /// <summary>
- /// 剪切文件
- /// </summary>
- /// <param name="source">原路径</param>
- /// <param name="destination">新路径</param>
- public bool FileMove(string source, string destination)
- {
- bool ret = false;
- FileInfo file_s = new FileInfo(source);
- FileInfo file_d = new FileInfo(destination);
- if (file_s.Exists)
- {
- if (!file_d.Exists)
- {
- file_s.MoveTo(destination);
- ret = true;
- }
- }
- if (ret == true)
- {
- //Response.Write("<script>alert('剪切文件成功!');</script>");
- }
- else
- {
- //Response.Write("<script>alert('剪切文件失败!');</script>");
- }
- return ret;
- }
- #endregion
- #region 检测指定目录是否为空
- /// <summary>
- /// 检测指定目录是否为空
- /// </summary>
- /// <param name="directoryPath">指定目录的绝对路径</param>
- public static bool IsEmptyDirectory(string directoryPath)
- {
- try
- {
- //判断文件是否存在
- string[] fileNames = GetFileNames(directoryPath);
- if (fileNames.Length > 0)
- {
- return false;
- }
- //判断是否存在文件夹
- string[] directoryNames = GetDirectories(directoryPath);
- if (directoryNames.Length > 0)
- {
- return false;
- }
- return true;
- }
- catch (Exception ex)
- {
- var s = ex.Message;
- return true;
- }
- }
- #endregion
- #region 获取指定目录中所有文件列表
- /// <summary>
- /// 获取指定目录中所有文件列表
- /// </summary>
- /// <param name="directoryPath">指定目录的绝对路径</param>
- public static string[] GetFileNames(string directoryPath)
- {
- if (!IsExistDirectory(directoryPath))
- {
- throw new FileNotFoundException();
- }
- return Directory.GetFiles(directoryPath);
- }
- #endregion
- #region 获取指定目录中的子目录列表
- /// <summary>
- /// 获取指定目录中所有子目录列表,若要搜索嵌套的子目录列表,请使用重载方法
- /// </summary>
- /// <param name="directoryPath">指定目录的绝对路径</param>
- public static string[] GetDirectories(string directoryPath)
- {
- try
- {
- return Directory.GetDirectories(directoryPath);
- }
- catch { throw; }
- }
- /// <summary>
- /// 获取指定目录及子目录中所有子目录列表
- /// </summary>
- /// <param name="directoryPath">指定目录的绝对路径</param>
- /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
- /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>
- /// <param name="isSearchChild">是否搜索子目录</param>
- public static string[] GetDirectories(string directoryPath, string searchPattern, bool isSearchChild)
- {
- try
- {
- if (isSearchChild)
- {
- return Directory.GetDirectories(directoryPath, searchPattern, SearchOption.AllDirectories);
- }
- else
- {
- return Directory.GetDirectories(directoryPath, searchPattern, SearchOption.TopDirectoryOnly);
- }
- }
- catch { throw; }
- }
- #endregion
- #region 获取一个文件的长度
- /// <summary>
- /// 获取一个文件的长度,单位为Byte
- /// </summary>
- /// <param name="filePath">文件的绝对路径</param>
- public static int GetFileSize(string filePath)
- {
- //创建一个文件对象
- FileInfo fi = new FileInfo(filePath);
- //获取文件的大小
- return (int)fi.Length;
- }
- /// <summary>
- /// 获取一个文件的长度,单位为KB
- /// </summary>
- /// <param name="filePath">文件的路径</param>
- public static double GetFileSizeByKb(string filePath)
- {
- //创建一个文件对象
- FileInfo fi = new FileInfo(filePath);
- //获取文件的大小
- return Math.Round(Convert.ToDouble(filePath.Length) / 1024, 2);// ConvertHelper.ToDouble(ConvertHelper.ToDouble(fi.Length) / 1024, 1);
- }
- /// <summary>
- /// 获取一个文件的长度,单位为MB
- /// </summary>
- /// <param name="filePath">文件的路径</param>
- public static double GetFileSizeByMb(string filePath)
- {
- //创建一个文件对象
- FileInfo fi = new FileInfo(filePath);
- //获取文件的大小
- return Math.Round(Convert.ToDouble(Convert.ToDouble(fi.Length) / 1024 / 1024), 2);
- }
- #endregion
- #region 获取所有文件夹及子文件夹
- /// <summary>
- /// 获取所有文件夹及子文件夹
- /// </summary>
- /// <param name="dirPath"></param>
- /// <returns></returns>
- public static List<ArrayFiles> GetDirs(string dirPath)
- {
- var list = new List<ArrayFiles>();
- return GetArrys(dirPath, 0, list);
- }
- private static int zdId = 0;
- private static List<ArrayFiles> GetArrys(string dirPath, int pid, List<ArrayFiles> list)
- {
- if (!Directory.Exists(dirPath)) return list;
- if (Directory.GetDirectories(dirPath).Length <= 0) return list;
- foreach (string path in Directory.GetDirectories(dirPath))
- {
- zdId++;
- var model = new ArrayFiles()
- {
- Id = zdId,
- Name = path.Substring(path.LastIndexOf('\\') + 1, path.Length - (path.LastIndexOf('\\') + 1)),
- Pid = pid,
- Open = false,
- Target = "DeployBase",
- Url = "/FytAdmin/FileMiam/DocList?path=" + path
- };
- list.Add(model);
- GetArrys(path, model.Id, list);
- }
- return list;
- }
- public class ArrayFiles
- {
- public int Id { get; set; }
- public int Pid { get; set; }
- public string Name { get; set; }
- public Boolean Open { get; set; }
- public string Target { get; set; }
- public string Url { get; set; }
- }
- #endregion
- #region 将文件读取到字符串中
- /// <summary>
- /// 将文件读取到字符串中
- /// </summary>
- /// <param name="filePath">文件的绝对路径</param>
- public static string FileToString(string filePath)
- {
- return FileToString(filePath, Encoding.UTF8);
- }
- /// <summary>
- /// 将文件读取到字符串中
- /// </summary>
- /// <param name="filePath">文件的绝对路径</param>
- /// <param name="encoding">字符编码</param>
- public static string FileToString(string filePath, Encoding encoding)
- {
- //创建流读取器
- StreamReader reader = new StreamReader(filePath, encoding);
- try
- {
- //读取流
- return reader.ReadToEnd();
- }
- catch { throw; }
- finally
- {
- //关闭流读取器
- reader.Close();
- }
- }
- #endregion
- /// <summary>
- /// 列出文件夹下的所有子文件及子文件夹的子文件
- /// </summary>
- /// <param name="directoryPath"></param>
- /// <returns></returns>
- public static List<string> ListAllFiles(string directoryPath)
- {
- List<string> filePaths = new List<string>();
- DirectoryInfo dirInfo = new DirectoryInfo(directoryPath);
- // 获取目录下的所有文件(包括子目录中的文件)
- FileInfo[] files = dirInfo.GetFiles("*", SearchOption.AllDirectories);
- foreach (FileInfo file in files)
- {
- filePaths.Add(file.FullName);
- // Console.WriteLine(file.FullName);
- }
- return filePaths;
- }
- }
- /// <summary>
- /// 远程文件下载
- /// </summary>
- public class HttpDldFile
- {
- /// <summary>
- /// Http方式下载文件
- /// </summary>
- /// <param name="url">http地址</param>
- /// <param name="localfile">本地文件</param>
- /// <returns></returns>
- public bool Download(string url, string localfile)
- {
- bool flag = false;
- long startPosition = 0; // 上次下载的文件起始位置
- FileStream writeStream; // 写入本地文件流对象
- long remoteFileLength = GetHttpLength(url);// 取得远程文件长度
- //System.Console.WriteLine("remoteFileLength=" + remoteFileLength);
- if (remoteFileLength == 745)
- {
- return false;
- }
- // 判断要下载的文件夹是否存在
- if (File.Exists(localfile))
- {
- writeStream = File.OpenWrite(localfile); // 存在则打开要下载的文件
- startPosition = writeStream.Length; // 获取已经下载的长度
- if (startPosition >= remoteFileLength)
- {
- writeStream.Close();
- return false;
- }
- else
- {
- writeStream.Seek(startPosition, SeekOrigin.Current); // 本地文件写入位置定位
- }
- }
- else
- {
- writeStream = new FileStream(localfile, FileMode.Create);// 文件不保存创建一个文件
- startPosition = 0;
- }
- try
- {
- HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(url);// 打开网络连接
- if (startPosition > 0)
- {
- myRequest.AddRange((int)startPosition);// 设置Range值,与上面的writeStream.Seek用意相同,是为了定义远程文件读取位置
- }
- Stream readStream = myRequest.GetResponse().GetResponseStream();// 向服务器请求,获得服务器的回应数据流
- byte[] btArray = new byte[512];// 定义一个字节数据,用来向readStream读取内容和向writeStream写入内容
- int contentSize = readStream.Read(btArray, 0, btArray.Length);// 向远程文件读第一次
- long currPostion = startPosition;
- while (contentSize > 0)// 如果读取长度大于零则继续读
- {
- currPostion += contentSize;
- int percent = (int)(currPostion * 100 / remoteFileLength);
- writeStream.Write(btArray, 0, contentSize);// 写入本地文件
- contentSize = readStream.Read(btArray, 0, btArray.Length);// 继续向远程文件读取
- }
- //关闭流
- writeStream.Close();
- readStream.Close();
- flag = true; //返回true下载成功
- }
- catch (Exception)
- {
- writeStream.Close();
- flag = false; //返回false下载失败
- }
- return flag;
- }
- // 从文件头得到远程文件的长度
- private static long GetHttpLength(string url)
- {
- long length = 0;
- try
- {
- HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);// 打开网络连接
- HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
- if (rsp.StatusCode == HttpStatusCode.OK)
- {
- length = rsp.ContentLength;// 从文件头得到远程文件的长度
- }
- rsp.Close();
- return length;
- }
- catch (Exception e)
- {
- var s = e.Message;
- return length;
- }
- }
- }
- }
|