using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Nirvana.Common
{
public class FileHelper
{
public static IWebHostEnvironment _hostingEnvironment;
public FileHelper(IWebHostEnvironment environment)
{
_hostingEnvironment = environment;
}
///
/// 获取文件的绝对路径,针对window程序和web程序都可使用
///
/// 相对路径地址
///
public static string GetAbsolutePath(string relativePath)
{
if (string.IsNullOrEmpty(relativePath))
{
throw new ArgumentNullException("参数relativePath空异常!");
}
relativePath = relativePath.Replace("/", "\\");
if (relativePath[0] == '\\')
{
relativePath = relativePath.Remove(0, 1);
}
//判断是Web程序还是window程序
if (_hostingEnvironment != null)
{
return Path.Combine(_hostingEnvironment.WebRootPath, relativePath);
}
else
{
return Path.Combine(AppContext.BaseDirectory, relativePath);
}
}
#region 检测指定目录是否存在
///
/// 检测指定目录是否存在
///
/// 目录的绝对路径
///
public static bool IsExistDirectory(string directoryPath)
{
return Directory.Exists(directoryPath);
}
#endregion
#region 删除文件
///
/// 删除文件
///
/// 要删除的文件路径和名称
public static void DeleteFile(string file)
{
if (System.IO.File.Exists(file))
{
System.IO.File.Delete(file);
}
}
public static FileStream GetFileStream(string fileName)
{
FileStream fileStream = null;
if (!string.IsNullOrEmpty(fileName) && System.IO.File.Exists(fileName))
{
fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
}
return fileStream;
}
#endregion
///
/// 读取文件(默认编码)
///
/// 文件路径
///
public static string Read(string path)
{
return Reads(path);
}
///
/// 读取文件,指定编码
///
///
///
///
public static string Reads(string path,Encoding encode=null)
{
if(encode == null)
{
encode = Encoding.Default;
}
return Read(GetAbsolutePath(path), encode);
}
///
/// 读取文件(指定编码)
///
/// 文件路径
/// 编码方式
///
public static string Read(string path, Encoding encode)
{
FileStream fs = null;
for (int i = 0; i < 5; i++)
{
try
{
fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
break;
}
catch
{
System.Threading.Thread.Sleep(50);
}
}
if (fs == null) return "";
StreamReader sr = null;
try
{
sr = new StreamReader(fs, encode);
return sr.ReadToEnd();
}
catch (Exception)
{
// throw ex;
return "";
}
finally
{
sr.Close();
fs.Close();
}
}
///
/// 返回文件行的数组
///
/// 文件路径
///
public static string[] ReadLines(string path)
{
return ReadLines(GetAbsolutePath(path), Encoding.Default);
}
///
/// 返回文件行的数组
///
/// 文件路径
/// 编码方式
///
public static string[] ReadLines(string path, Encoding encode)
{
try
{
return System.IO.File.ReadAllLines(path, encode);
}
catch (Exception)
{
// throw ex;
return null;
}
}
}
}