using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
namespace GuruClient
{
public static partial class Utility
{
///
/// 文件工具
/// 正则表达式测试地址:https://www.regexpal.com
///
public static partial class Files
{
///
/// 文件夹是否可写
///
///
///
public static bool HasWriteAccess(string path)
{
if (!Directory.Exists(path)) return false;
try
{
string tmpFilePath = Path.Combine(path, System.IO.Path.GetRandomFileName());
using (FileStream fs = new FileStream(tmpFilePath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite))
{
StreamWriter writer = new StreamWriter(fs);
writer.Write("1");
}
File.Delete(tmpFilePath);
return true;
}
catch
{
return false;
}
}
///
/// 获取所有文件路径
///
///
///
///
public static string[] GetFiles(string path, params string[] extents)
{
if (extents.Length > 0)
{
return Directory.GetFiles(path, "*.*", SearchOption.AllDirectories)
.Where(f => extents.Contains(Path.GetExtension(f))).ToArray();
}
else
{
return Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
}
}
///
/// 获取传入后缀以外的所有文件
///
///
///
///
public static string[] GetFilesExcept(string path, params string[] extents)
{
if (extents.Length > 0)
{
return Directory.GetFiles(path, "*.*", SearchOption.AllDirectories)
.Where(f => !extents.Contains(Path.GetExtension(f))).ToArray();
}
else
{
return Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
}
}
///
/// 删除文件夹
///
///
///
public static bool DeleteDir(string path)
{
try
{
if (string.IsNullOrEmpty(path)) return true;
if (!Directory.Exists(path)) return true;
Directory.Delete(path, true);
return true;
}
catch (System.Exception ex)
{
Debug.Log(string.Format("SafeDeleteDir failed! path = {0} with err: {1}", path, ex.Message));
return false;
}
}
///
/// 删除文件
///
///
///
public static bool DeleteFile(string path)
{
try
{
if (string.IsNullOrEmpty(path)) return true;
if (!File.Exists(path)) return true;
File.Delete(path);
return true;
}
catch (System.Exception ex)
{
Debug.Log(string.Format("DeleteFile failed! path = {0} with err: {1}", path, ex.Message));
return false;
}
}
///
/// 删除指定文件夹下所有文件
///
///
///
public static void DeleteFiles(string path, params string[] extents)
{
var files = GetFiles(path, extents);
for (var i = 0; i < files.Length; i++) DeleteFile(files[i]);
}
///
/// 删除指定文件夹下所有文件
///
///
///
public static void DeleteFilesExcept(string path, params string[] extents)
{
var files = GetFilesExcept(path, extents);
for (var i = 0; i < files.Length; i++) DeleteFile(files[i]);
}
///
/// 清除空文件夹
///
///
/// 根目录为空时,是否删除根目录
public static void DeleteEmptyDirs(string path, bool self = false)
{
if (!Directory.Exists(path)) return;
// 获取所有文件夹和文件
var entries = Directory.GetFileSystemEntries(path, "*", SearchOption.AllDirectories);
if (entries.Length > 0)
{
foreach (var p in entries)
{
// 跳过文件,只考虑文件夹
if (File.Exists(p)) continue;
if (Directory.Exists(p))
{
// 如果文件夹里没有了文件,则删除这个文件夹
var files = Directory.GetFiles(p, "*", SearchOption.AllDirectories);
if (files.Length == 0) Directory.Delete(p, true);
}
}
// 删除自己
if (self)
{
entries = Directory.GetFileSystemEntries(path, "*", SearchOption.AllDirectories);
if (entries.Length == 0) Directory.Delete(path);
}
}
else
{
// 删除自己
if (self) Directory.Delete(path);
}
}
///
/// 重命名文件
///
///
///
///
public static bool RenameFile(string sourceFileName, string destFileName)
{
try
{
if (string.IsNullOrEmpty(sourceFileName)) return false;
if (!File.Exists(sourceFileName)) return false;
DeleteFile(destFileName);
File.Move(sourceFileName, destFileName);
return true;
}
catch (System.Exception ex)
{
Debug.Log(string.Format("RenameFile failed! path = {0} with err: {1}", sourceFileName, ex.Message));
return false;
}
}
///
/// 读取字节数组
///
///
///
public static byte[] ReadAllBytes(string path)
{
try
{
if (string.IsNullOrEmpty(path)) return null;
if (!File.Exists(path)) return null;
return File.ReadAllBytes(path);
// return Encoding.UTF8.GetBytes(File.ReadAllText(path));
}
catch (System.Exception ex)
{
Debug.Log($"ReadAllBytes failed! path = {path} with err = {ex.Message}");
return null;
}
}
///
/// 将字节数组写入指定文件
///
///
///
///
public static bool WriteAllBytes(string path, byte[] bytes)
{
try
{
if (string.IsNullOrEmpty(path)) return false;
var dir = Path.GetDirectoryName(path);
if (Directory.Exists(dir)) Directory.CreateDirectory(dir);
if (!File.Exists(path)) return false;
File.WriteAllBytes(path, bytes);
return true;
}
catch (System.Exception ex)
{
Debug.Log(string.Format("WriteAllBytes failed! path = {0} with err = {1}", path, ex.Message));
return false;
}
}
///
/// 将字符串写入指定文件
///
/// 文件路径
/// 文件内容
///
public static bool WriteStringToFile(string path, string content)
{
try
{
if (string.IsNullOrEmpty(path)) return false;
var dir = Path.GetDirectoryName(path);
if (Directory.Exists(dir)) Directory.CreateDirectory(dir);
//这里的FileMode.create是创建这个文件,如果文件名存在则覆盖重新创建
FileStream fs = new FileStream(path, FileMode.Create);
//存储时时二进制,所以这里需要把我们的字符串转成二进制
byte[] bytes = new UTF8Encoding().GetBytes(content);
fs.Write(bytes, 0, bytes.Length);
//每次读取文件后都要记得关闭文件
fs.Close();
return true;
}
catch (System.Exception e)
{
Debug.Log(e);
return false;
}
}
///
/// 从文件读取内容
///
/// 文件路径
///
public static string ReadStringFromFile(string path)
{
try
{
if (string.IsNullOrEmpty(path)) return "";
if (File.Exists(path))
{
FileStream fs = new FileStream(path, FileMode.Open);
byte[] bytes = new byte[fs.Length];
fs.Read(bytes, 0, bytes.Length);
string content = new UTF8Encoding().GetString(bytes);
fs.Close();
return content;
}
return "";
}
catch (System.Exception e)
{
Debug.Log(e);
return "";
}
}
//从StreamingAssets拷贝到读写目录
public static void CopyStreamingAssetsFile(string from, string dest)
{
try
{
if (Application.platform == RuntimePlatform.Android)
{
using (UnityWebRequest request = UnityWebRequest.Get(Application.streamingAssetsPath + "/" + from))
{
request.timeout = 5;
request.downloadHandler = new DownloadHandlerFile(dest);//直接将文件下载到外存
request.SendWebRequest();
//等待下载完成
while (!request.isDone){}
request.Abort();
//默认值是true,调用该方法不需要设置Dispose(),Unity就会自动在完成后调用Dispose()释放资源。
request.disposeDownloadHandlerOnDispose = true;
request.Dispose();
}
}
else
{
File.Copy(Application.streamingAssetsPath + "/" + from, dest, true);
}
}
catch (System.Exception e)
{
}
}
///
///读取StreamingAssets中的文件
///
/// StreamingAssets下的文件路径
/// 读取到的字符串
public static string GetTextFromStreamingAssets(string path)
{
string localPath = "";
if (Application.platform == RuntimePlatform.Android)
{
localPath = Application.streamingAssetsPath + "/" + path;
}
else
{
localPath = "file:///" + Application.streamingAssetsPath + "/" + path;
}
UnityWebRequest requrest = UnityWebRequest.Get(localPath);
var operation = requrest.SendWebRequest();
while (!operation.isDone)
{
}
if (requrest.result == UnityWebRequest.Result.ConnectionError || requrest.result == UnityWebRequest.Result.ProtocolError)
{
return "";
}
else
{
return requrest.downloadHandler.text;
}
}
}
}
}