關於檔案資源操作總結
阿新 • • 發佈:2021-01-06
技術標籤:unity
/// <summary> /// 獲取路徑下所有的資料夾名字 /// </summary> /// <param name="path">目標路徑</param> /// <returns></returns> public List<string> GetFileNameList(string path) { List<string> file_name_list = new List<string>(); var dirInfo = new DirectoryInfo(path); foreach (var child in dirInfo.GetDirectories()) { //print(child); file_name_list.Add(child.Name); } return file_name_list; }
讀取資料夾下所有的資源名字
public List<string> ReadFolder(string folder, string imgtype, bool is_content = true) { List<string> res_name_list = new List<string>(); //獲取指定路徑下面的所有資原始檔 if (is_content) folder = this.path + folder; if (Directory.Exists(folder)) { DirectoryInfo direction = new DirectoryInfo(folder); FileInfo[] files = direction.GetFiles("*", SearchOption.AllDirectories); string[] ImageType = imgtype.Split('|'); //找到最後一張照片的路徑 開始下載儲存盤 for (int j = 0; j < files.Length; j++) { for (int i = 0; i < ImageType.Length; i++) { if ((files[j].Name.EndsWith(ImageType[i]) || files[j].Name.EndsWith(ImageType[i].ToLower()))) { //Debug.Log(j + "Name:" + folder + "/" + files[j].Name); //打印出來這個檔案架下的所有檔案 //載入顯示照片 res_name_list.Add(folder + "/" + files[j].Name); } } } } else { return null; } return res_name_list; }
通過路徑載入圖片
#region 通過路徑獲取Sprite /// <summary> /// 通過路徑獲取Sprite /// </summary> /// <param name="path_name">路徑+圖片名字</param> /// <returns></returns> public Sprite LoadPhoto(string path_name) { if (!File.Exists(path_name)) return null; Texture2D tx = new Texture2D(256, 256); tx.LoadImage(getImageByte(path_name)); Sprite sprite = SetSprites(tx); return sprite; } /// <summary> /// 根據圖片路徑返回圖片的位元組流byte[] /// </summary> /// <param name="imagePath">圖片路徑</param> /// <returns>返回的位元組流</returns> public static byte[] getImageByte(string imagePath) { FileStream files = new FileStream(imagePath, FileMode.Open); byte[] imgByte = new byte[files.Length]; files.Read(imgByte, 0, imgByte.Length); files.Close(); files.Dispose(); return imgByte; } public Sprite SetSprites(Texture2D texture2D) { return Sprite.Create(texture2D, new Rect(0, 0, texture2D.width, texture2D.height), new Vector2(0.5f, 0.5f)); } #endregion
通過資源名字或者路徑判斷資源型別(圖片或者其他)
/// <summary>
/// 是否為圖片
/// </summary>
/// <param name="path_name">完整路徑</param>
/// <returns></returns>
public bool IsImage(string path_name)
{
string[] s1 = path_name.Split('/');
string imgtype = ".JPEG|.JPG|.PNG";
string[] ImageType = imgtype.Split('|');
for (int i = 0; i < ImageType.Length; i++)
{
if (s1[s1.Length - 1].Contains(ImageType[i]))
return true;
}
return false;
}