20220510_191_upperpc/FTP/Models/FilesHelper.cs

763 lines
30 KiB
C#
Raw Permalink Normal View History

2023-07-27 02:57:34 +00:00
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
namespace FTP.Models
{
public class FilesHelper
{
public Dictionary<string, string> directorys = new Dictionary<string, string>();
public List<string> lists = new List<string>();
OperationResult operation = new OperationResult();
public int count = 1;
public string counts;
bool flag;
#region Windows目录下的文件和文件夹,
/// <summary>
/// 递归获取Windows目录下的文件和文件夹
/// </summary>
/// <param name="sourcePath">文件绝对路径</param>
/// <returns></returns>
public Tuple<OperationResult, List<string>, Dictionary<string, string>> GetDirectoryAndFile(string sourcePath)
{
GetDirectory(sourcePath);
if (lists.Count > 0)
{
operation.isOk = true;
operation.returnValue = "获取递归文件夹和文件列表成功";
return new Tuple<OperationResult, List<string>, Dictionary<string, string>>(operation, lists, directorys);
}
operation.isOk = false;
operation.returnValue = "获取递归文件夹和文件列表失败";
return new Tuple<OperationResult, List<string>, Dictionary<string, string>>(operation, lists, directorys);
}
/// <summary>
/// 递归获取Windows目录下的文件和文件夹
/// </summary>
/// <param name="sourcePath">文件绝对路径</param>
private void GetDirectory(string sourcePath)
{
try
{
//判断源文件夹是否存在
if (Directory.Exists(sourcePath))
{
//获取源文件夹中的目录及文件路径,存入字符串
string[] tmp = Directory.GetFileSystemEntries(sourcePath);
//循环遍历
for (int i = 0; i < tmp.Length; i++)
{
//如果是文件则存入FileList
if (File.Exists(tmp[i]))
{
counts = (++count).ToString();
lists.Add(sourcePath);
directorys.Add(counts, tmp[i]);
}
else
{
GetDirectory(tmp[i]);
}
}
}
}
catch (Exception ex)
{
return;
}
}
#endregion
//#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 OperationResult 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)
// {
// operation.isOk = false;
// operation.tRes = "只能上传小于" + maxLength.ToString() + "的文件!";
// return operation;
// }
// //取得上传文件之扩展文件名,并转换成小写字母
// 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)
// {
// operation.isOk = false;
// operation.tRes = "文件上传错误,错误原因:" + ex.ToString();
// return operation;
// }
// }
// else
// {
// operation.isOk = false;
// operation.tRes = "文件格式不符,可以上传的文件格式为:" + tmp;
// return operation;
// }
// }
// else
// {
// operation.isOk = false;
// operation.tRes = "请选择要上传的文件!";
// return operation;
// }
// operation.isOk = true;
// operation.tRes = "文件上传成功!";
// return operation;
//}
//#endregion
#region
/// <summary>
/// 返回文件是否存在
/// </summary>
/// <param name="SouthPath">文件地址</param>
/// <returns>是否存在</returns>
public OperationResult FileExists(string SouthPath)
{
flag = System.IO.File.Exists(SouthPath);
if (flag)
{
operation.tRes = "文件存在!";
}
else
{
operation.tRes = "文件不存在!";
}
operation.isOk = flag;
return operation;
}
#endregion
#region
/// <summary>
/// 判断文件名是否为浏览器可以直接显示的图片文件名
/// </summary>
/// <param name="filename">文件名</param>
/// <returns>是否可以直接显示</returns>
public OperationResult IsImgFilename(string filename)
{
filename = filename.Trim();
if (filename.EndsWith(".") || filename.IndexOf(".") == -1)
{
operation.isOk = false;
operation.tRes = "文件不可以直接显示!";
return operation;
}
string extname = filename.Substring(filename.LastIndexOf(".") + 1).ToLower();
flag = (extname == "jpg" || extname == "jpeg" || extname == "png" || extname == "bmp" || extname == "gif");
if (flag)
{
operation.tRes = "文件可以直接显示!";
}
operation.isOk = flag;
operation.tRes = "文件不可以直接显示!";
return operation;
}
#endregion
#region
/// <summary>
/// 复制当前目录的所有文件
/// </summary>
/// <param name="sourceDir">原始目录</param>
/// <param name="targetDir">目标目录</param>
/// <param name="overWrite">如果为true,覆盖同名文件,否则不覆盖</param>
/// <param name="copySubDir">如果为true,包含子目录,否则不包含</param>
public OperationResult CopyAllFiles(string sourceDir, string targetDir, bool overWrite, bool copySubDir)
{
//目录不存在首先创建目录
if (!Directory.Exists(targetDir))
{
Directory.CreateDirectory(targetDir);
}
try
{
//辅助当前目录文件
foreach (string sourceFileName in Directory.GetFiles(sourceDir))
{
string targetFileName = Path.Combine(targetDir, sourceFileName.Substring(sourceFileName.LastIndexOf('\\') + 1));
if (File.Exists(targetFileName))
{
if (overWrite == true)
{
File.SetAttributes(targetFileName, FileAttributes.Normal);
File.Copy(sourceFileName, targetFileName, overWrite);
}
}
else
{
File.Copy(sourceFileName, targetFileName, overWrite);
}
}
if (copySubDir)
{
foreach (string sourceSubDir in Directory.GetDirectories(sourceDir))
{
string targetSubDir = Path.Combine(targetDir, sourceSubDir.Substring(sourceSubDir.LastIndexOf('\\') + 1));
if (!Directory.Exists(targetSubDir))
{
Directory.CreateDirectory(targetSubDir);
}
CopyAllFiles(sourceSubDir, targetSubDir, overWrite, true);
}
}
operation.isOk = true;
operation.returnValue = string.Format("复制目录 {0}的文件到目录 {1}成功,总计复制{2}个文件!", sourceDir, targetDir, count.ToString());
}
catch (Exception ex)
{
operation.isOk = false;
operation.returnValue = string.Format("复制目录 {0}的文件到目录 {1}失败,失败原因:{3}!", sourceDir, targetDir, ex.ToString());
}
return operation;
}
#endregion
#region /
/// <summary>
/// 移动当前目录的文件
/// </summary>
/// <param name="sourceDir">原始目录</param>
/// <param name="targetDir">目标目录</param>
/// <param name="overWrite">如果为true,覆盖同名文件,否则不覆盖</param>
/// <param name="moveSubDir">如果为true,包含目录,否则不包含</param>
public OperationResult MoveFiles(string sourceDir, string targetDir, bool overWrite, bool moveSubDir)
{
//目录不存在首先创建目录
if (!Directory.Exists(targetDir))
{
Directory.CreateDirectory(targetDir);
}
try
{
//移动当前目录文件
foreach (string sourceFileName in Directory.GetFiles(sourceDir))
{
string targetFileName = Path.Combine(targetDir, sourceFileName.Substring(sourceFileName.LastIndexOf('\\') + 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('\\') + 1));
if (!Directory.Exists(targetSubDir))
{
Directory.CreateDirectory(targetSubDir);
}
MoveFiles(sourceSubDir, targetSubDir, overWrite, true);
Directory.Delete(sourceSubDir);
}
}
operation.isOk = true;
operation.returnValue = string.Format("移动目录 {0}的所有文件到目录 {1}成功!", sourceDir, targetDir);
}
catch (Exception ex)
{
operation.isOk = false;
operation.returnValue = string.Format("移动目录 {0}的所有文件到目录 {1}失败,失败原因:{3}!", sourceDir, targetDir, ex.ToString());
}
return operation;
}
#endregion
#region
/// <summary>
/// 删除指定目录的所有文件和子目录
/// </summary>
/// <param name="TargetDir">操作目录</param>
/// <param name="delSubDir">如果为true,包含对子目录的操作</param>
public OperationResult DeleteDirectoryFiles(string TargetDir, bool delSubDir)
{
//判断目录是否存在
flag = Directory.Exists(TargetDir);
try
{
if (flag)
{
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();
}
}
operation.returnValue = string.Format("删除目录 {0} 下的文件成功", TargetDir);
}
}
catch (Exception ex)
{
operation.returnValue = string.Format("删除目录 {0} 下的文件失败", TargetDir);
}
operation.isOk = flag;
return operation;
}
#endregion
#region
/// <summary>
/// 删除文件
/// </summary>
/// <param name="sourcePath">文件路径</param>
public OperationResult DeleteFiles(string sourcePath)
{
//判断目录是否存在
flag = File.Exists(sourcePath);
try
{
if (flag)
{
File.Delete(sourcePath);
}
operation.isOk = true;
operation.returnValue = string.Format("删除路径 {0} 下的文件成功", sourcePath);
}
catch (Exception ex)
{
operation.isOk = false;
operation.returnValue = string.Format("删除路径 {0} 下的文件失败,失败原因:{1}", sourcePath, ex.ToString());
}
return operation;
}
#endregion
#region
/// <summary>
/// 创建指定目录
/// </summary>
/// <param name="targetDir"></param>
public OperationResult CreateDirectory(string targetDir)
{
DirectoryInfo dir = new DirectoryInfo(targetDir);
flag = dir.Exists;
try
{
if (!flag)
{
dir.Create();
}
operation.isOk = !flag;
operation.returnValue = string.Format("创建指定目录{0}成功", targetDir);
}
catch (Exception ex)
{
operation.isOk = false;
operation.returnValue = string.Format("创建指定目录{0}失败,失败原因{1}", targetDir, ex.ToString());
}
return operation;
}
#endregion
#region
/// <summary>
/// 建立子目录
/// </summary>
/// <param name="parentDir">目录路径</param>
/// <param name="subDirName">子目录名称</param>
public OperationResult CreateChildDirectory(string parentDir, string subDirName)
{
string path = parentDir + "\\" + subDirName;
return CreateDirectory(path);
}
#endregion
#region
/// <summary>
/// 重命名文件夹
/// </summary>
/// <param name="OldFloderName">原路径文件夹名称</param>
/// <param name="NewFloderName">新路径文件夹名称</param>
/// <returns></returns>
public bool ReNameFloder(string OldFloderName, string NewFloderName)
{
try
{
if (Directory.Exists(OldFloderName))
{
Directory.Move(OldFloderName, NewFloderName);
}
return true;
}
catch
{
return false;
}
}
#endregion
#region
/// <summary>
/// 删除指定目录
/// </summary>
/// <param name="targetDir">目录路径</param>
public OperationResult DeleteDirectory(string targetDir)
{
DirectoryInfo dirInfo = new DirectoryInfo(targetDir);
if (dirInfo.Exists)
{
return DeleteDirectoryFiles(targetDir, true);
}
operation.isOk = false;
operation.returnValue = string.Format("目录{0}不存在", targetDir);
return operation;
}
#endregion
#region
/// <summary>
/// 检测目录是否存在
/// </summary>
/// <param name="StrPath">路径</param>
/// <returns></returns>
public bool DirectoryIsExists(string StrPath)
{
DirectoryInfo dirInfo = new DirectoryInfo(StrPath);
return dirInfo.Exists;
}
/// <summary>
/// 检测目录是否存在
/// </summary>
/// <param name="StrPath">路径</param>
/// <param name="Create">如果不存在,是否创建</param>
public void DirectoryIsExists(string StrPath, bool Create)
{
DirectoryInfo dirInfo = new DirectoryInfo(StrPath);
flag = DirectoryIsExists(StrPath);
if (!flag)
{
if (Create)
{
dirInfo.Create();
}
}
}
#endregion
#region ,
/// <summary>
/// 删除指定目录的所有子目录,不包括对当前目录文件的删除
/// </summary>
/// <param name="targetDir">目录路径</param>
public OperationResult DeleteSubDirectory(string targetDir)
{
flag = DirectoryIsExists(targetDir);
if (flag)
{
foreach (string subDir in Directory.GetDirectories(targetDir))
{
DeleteDirectory(subDir);
}
operation.returnValue = string.Format("删除目录{0}下的所有子目录成功", targetDir);
}
operation.isOk = flag;
operation.returnValue = string.Format("目录{0}不存在", targetDir);
return operation;
}
#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="OldFileName">旧文件真实路径</param>
/// <param name="NewFileName">新文件真实路径</param>
/// <returns></returns>
public OperationResult RenameFile(string OldFileName, string NewFileName)
{
flag = File.Exists(OldFileName);
if (flag)
{
File.Move(OldFileName, NewFileName);
operation.isOk = flag;
operation.returnValue = string.Format("旧文件{0}重命名为新文件{1}成功", OldFileName, NewFileName);
return operation;
}
operation.isOk = flag;
operation.returnValue = string.Format("旧文件{0}不存在", OldFileName);
return operation;
}
#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;
}
return false;
}
#endregion
#region
/// <summary>
/// 以只读方式读取文本文件
/// </summary>
/// <param name="FilePath">文件路径及文件名</param>
/// <returns></returns>
public string ReadTxtFile(string FilePath)
{
flag = File.Exists(FilePath);
string content = "";//返回的字符串
if (flag)
{
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 OperationResult WriteStrToTxtFile(string FilePath, string WriteStr, FileMode FileModes)
{
flag = File.Exists(FilePath);
operation.isOk = flag;
if (flag)
{
FileStream fst = new FileStream(FilePath, FileModes);
StreamWriter swt = new StreamWriter(fst, Encoding.GetEncoding("utf-8"));
swt.WriteLine(WriteStr);
swt.Close();
fst.Close();
operation.returnValue = string.Format("写入为文件{0}数据成功", FilePath);
return operation;
}
operation.returnValue = string.Format("文件{0}不存在", FilePath);
return operation;
}
#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;
return null;
}
#endregion
#region BKBGBTB方式表示[+2 ]
/// <summary>
/// 获取文件大小并以BKBGBTB方式表示
/// </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>
/// 获取文件大小并以BKBGBTB方式表示
/// </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 Http下载文件
///// <summary>
///// 下载文件
///// </summary>
///// <param name="FileFullPath">下载文件下载的完整路径及名称</param>
//public void DownLoadFiles(string FileFullPath)
//{
// if (!string.IsNullOrEmpty(FileFullPath) && (FileExists(FileFullPath)).isOk)
// {
// 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
}
}