using System.Text;
namespace Atomx.Utils.Extension
{
public static class PathExtension
{
///
/// 是否是绝对路径
/// windows下判断 路径是否包含 ":"
/// Mac OS、Linux下判断 路径是否包含 "\"
///
///
///
public static bool IsAbsolute(this string path)
{
return Path.VolumeSeparatorChar == ':' ? path.IndexOf(Path.VolumeSeparatorChar) > 0 : path.IndexOf('\\') > 0;
}
///
/// 获取文件绝对路径
///
///
///
public static string MapPath(string root, string path)
{
return path.IsAbsolute() ? path : Path.Combine(root, path.TrimStart('~', '/').Replace('/', Path.DirectorySeparatorChar));
}
///
/// 检测指定路径是否存在
///
/// 路径
/// 是否是目录
///
public static bool IsExist(string root, string path, bool isDirectory)
{
if (isDirectory)
{
return Directory.Exists(path.IsAbsolute() ? path : MapPath(root, path));
}
else
{
return File.Exists(path.IsAbsolute() ? path : MapPath(root, path));
}
}
///
/// 根据指定目录,当前日期和扩展名,获取一个完整的存储路径和名称
///
/// 指定存储文件根目录,默认 upload,
/// 是否固定存储在根目录,如果不固定,将自动根据时间生成子文件夹进行存储
/// 存储文件名,如果为空将自动生成文件名
/// 文件存储后缀,不能为空
///
public static string GetFileNameByData(string path, bool fixedpath, string name, string extension)
{
if (string.IsNullOrEmpty(extension)) throw new ArgumentNullException("extension");
if (!extension.StartsWith(".")) extension = "." + extension;
if (string.IsNullOrEmpty(path))
{
path = "/uploads";
}
if (path.StartsWith("/")) path = path.Substring(1, path.Length - 1);
if (path.EndsWith("/")) path = path.Substring(0, path.Length - 1);
StringBuilder fileName = new StringBuilder(path);
if (!fixedpath)
{
fileName.AppendFormat("/{0}/{1}/", DateTime.Now.ToString("yyyyMM"), DateTime.Now.ToString("dd"));
}
if (string.IsNullOrEmpty(name))
{
Random random = new Random(Guid.NewGuid().GetHashCode());
fileName.Append(DateTime.Now.ToString("yyyyMMddHHmmss") + random.Next(1000, 10000));
}
else
{
fileName.Append("/" + name);
}
return fileName.ToString() + extension;
}
}
}