unity_art_puzzle_playable_luna/APPlayableLuna/Assets/Utility.FIles.cs

381 lines
14 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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
{
/// <summary>
/// 文件工具
/// 正则表达式测试地址https://www.regexpal.com
/// </summary>
public static partial class Files
{
/// <summary>
/// 文件夹是否可写
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
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;
}
}
/// <summary>
/// 获取所有文件路径
/// </summary>
/// <param name="path"></param>
/// <param name="extents"></param>
/// <returns></returns>
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);
}
}
/// <summary>
/// 获取传入后缀以外的所有文件
/// </summary>
/// <param name="path"></param>
/// <param name="extents"></param>
/// <returns></returns>
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);
}
}
/// <summary>
/// 删除文件夹
/// </summary>
/// <param name="folderPath"></param>
/// <returns></returns>
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;
}
}
/// <summary>
/// 删除文件
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
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;
}
}
/// <summary>
/// 删除指定文件夹下所有文件
/// </summary>
/// <param name="path"></param>
/// <param name="extents"></param>
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]);
}
/// <summary>
/// 删除指定文件夹下所有文件
/// </summary>
/// <param name="path"></param>
/// <param name="extents"></param>
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]);
}
/// <summary>
/// 清除空文件夹
/// </summary>
/// <param name="path"></param>
/// <param name="self">根目录为空时,是否删除根目录</param>
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);
}
}
/// <summary>
/// 重命名文件
/// </summary>
/// <param name="sourceFileName"></param>
/// <param name="destFileName"></param>
/// <returns></returns>
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;
}
}
/// <summary>
/// 读取字节数组
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
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;
}
}
/// <summary>
/// 将字节数组写入指定文件
/// </summary>
/// <param name="path"></param>
/// <param name="bytes"></param>
/// <returns></returns>
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;
}
}
/// <summary>
/// 将字符串写入指定文件
/// </summary>
/// <param name="path">文件路径</param>
/// <param name="content">文件内容</param>
/// <returns></returns>
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;
}
}
/// <summary>
/// 从文件读取内容
/// </summary>
/// <param name="path">文件路径</param>
/// <returns></returns>
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)
{
}
}
/// <summary>
///读取StreamingAssets中的文件
/// </summary>
/// <param name="path">StreamingAssets下的文件路径</param>
/// <returns>读取到的字符串</returns>
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;
}
}
}
}
}