IO流是C#語(yǔ)言中對(duì)文件操作常用的方式,但在Unity跨平臺(tái)開(kāi)發(fā)中需要注意有些平臺(tái)不支持IO,有些平臺(tái)的只讀文件不支持支持操作,例如安卓平臺(tái)的讀取StreamingAsset文件夾等。
大部分項(xiàng)目中都會(huì)有大量的對(duì)文件操作需求,因此我使用IO流整理編寫了一些常用的對(duì)文件操作方法,需要注意因?yàn)槭褂肐O流操作,因此不支持讀取遠(yuǎn)端文件,同時(shí)也不支持前面提及的某些平臺(tái)或者某些路徑中的文件操作不支持。
由于目前腳本中沒(méi)有使用Unity特有的類,所以下面腳本在,單純的C#項(xiàng)目中可以使用!
下面列舉下該腳本中提供的方法,以及完整腳本(目前就這么多,后續(xù)會(huì)不斷迭代更新,初步想法增加加載遠(yuǎn)端文件,以及加載一些不能用IO流加載的文件):
方法列表:
1、判斷文件或文件夾是否存在
2、判斷文件是否存在并且不為0字節(jié)
3、創(chuàng)建文件夾
4、刪除文件
5、導(dǎo)出文件(可以是文本文件,包含多個(gè)重載)
6、獲取設(shè)備所有盤符
7、獲取文件夾下所有文件夾路徑
8、獲取文件夾下所有文件路徑
9、獲取文件夾下指定類型文件路徑
10、獲取文件夾下除指定類型外的所有文件路徑
11、加載文件(可加載被其他進(jìn)程打開(kāi)的文件)
12、加載多個(gè)文件(可加載被其他進(jìn)程打開(kāi)的文件)
13、加載文本文件(可加載被其他進(jìn)程打開(kāi)的文件)
14、刪除文件夾下指定后綴的文件
15、刪除文件夾下除指定后綴的文件
16、刪除指定文件目錄下的所有文件
17、刪除指定文件夾(包括文件夾內(nèi)的子文件夾以及所有文件)文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-707610.html
代碼如下:文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-707610.html
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public static class FilesTool
{
/// <summary>
/// 文件操作緩存
/// </summary>
public static int bufferSize = 2048 * 2048;
/// <summary>
/// 判斷文件是否存在
/// </summary>
/// <param name="FilePath">文件路徑</param>
/// <returns>返回bool,true為存在,false不存在</returns>
public static bool IsHaveFile(string FilePath)
{
if (File.Exists(FilePath))
return true;
else
return Directory.Exists(FilePath);
}
/// <summary>
/// 判斷文件是否為0字節(jié)
/// </summary>
/// <param name="FilePath"></param>
/// <returns></returns>
public static bool IsFileHasData(string FilePath, Action<bool,FileDataInfo> completed = null)
{
try
{
var data = LoadFile(FilePath);
completed?.Invoke(data.Data != null && data.Data.Length > 0, data);
return data.Data!=null&&data.Data.Length > 0;
}
catch (Exception ex)
{
Console.WriteLine($"代碼運(yùn)行錯(cuò)誤!Error={ex.StackTrace}");
completed?.Invoke(false, null);
return false;
}
}
/// <summary>
/// 創(chuàng)建文件
/// </summary>
/// <param name="FilePath">文件路徑</param>
/// <param name="IfHaveFileIsCreate">當(dāng)文件存在時(shí)是否重新創(chuàng)建</param>
/// <returns>返回bool,true為創(chuàng)建成功,false沒(méi)有創(chuàng)建</returns>
public static bool CreateFile(string FilePath, bool IfHaveFileIsCreate = false)
{
if (!Directory.Exists(FilePath))
{
Directory.CreateDirectory(FilePath);
return true;
}
else
{
if (IfHaveFileIsCreate)
{
Directory.CreateDirectory(FilePath);
return true;
}
else
{
return false;
}
}
}
/// <summary>
/// 刪除指定文件
/// </summary>
/// <param name="FilePath">文件路徑</param>
/// <returns>返回bool,true為刪除成功,false為刪除失敗</returns>
public static bool DeleteFile(string FilePath)
{
if (Directory.Exists(FilePath))
{
File.Delete(FilePath);
return true;
}
else
{
return false;
}
}
/// <summary>
/// 導(dǎo)出文本文件
/// </summary>
/// <param name="fileContent">文件內(nèi)容</param>
/// <param name="filePath">文件保存路徑</param>
/// <param name="fileName">文件名以及后綴</param>
/// <returns>返回bool,true導(dǎo)出成功,false導(dǎo)出失敗</returns>
public static bool ExportFile(string content, string filePath, string fileName, FileMode fileMode = FileMode.Truncate)
{
try
{
CreateFile(filePath);
var path = Path.Combine(filePath, fileName);
fileMode = IsFileHasData(path) ? fileMode : FileMode.CreateNew;
var fileAccess = fileMode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite;
using (FileStream nFile = new FileStream(path, fileMode, fileAccess, FileShare.ReadWrite, bufferSize))
{
using (StreamWriter sWriter = new StreamWriter(nFile))
{
//寫入數(shù)據(jù)
sWriter.Write(content);
return true;
}
}
}
catch (Exception ex)
{
Console.Write($"導(dǎo)出失敗: {ex.StackTrace}");
return false;
}
}
/// <summary>
/// 導(dǎo)出文本文件
/// </summary>
/// <param name="fileContent">文件內(nèi)容</param>
/// <param name="fileFullPath">文件保存路徑</param>
/// <returns>返回bool,true導(dǎo)出成功,false導(dǎo)出失敗</returns>
public static bool ExportFile(string content, string fileFullPath, FileMode fileMode = FileMode.Truncate)
{
try
{
var filePath = Path.GetDirectoryName(fileFullPath);
CreateFile(filePath);
fileMode = IsFileHasData(fileFullPath) ? fileMode : FileMode.CreateNew;
var fileAccess = fileMode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite;
using (FileStream nFile = new FileStream(fileFullPath, fileMode, fileAccess, FileShare.ReadWrite, bufferSize))
{
using (StreamWriter sWriter = new StreamWriter(nFile))
{
//寫入數(shù)據(jù)
sWriter.Write(content);
return true;
}
}
}
catch (Exception ex)
{
Console.Write($"導(dǎo)出失敗: {ex.StackTrace}");
return false;
}
}
/// <summary>
/// 導(dǎo)出文本文件
/// </summary>
/// <param name="fileContent">文件內(nèi)容</param>
/// <param name="filePath">文件保存路徑</param>
/// <param name="fileName">文件名以及后綴</param>
/// <returns>返回bool,true導(dǎo)出成功,false導(dǎo)出失敗</returns>
public static bool ExportFile(string content, Encoding encoding, string filePath, string fileName, FileMode fileMode = FileMode.Truncate)
{
try
{
CreateFile(filePath);
var path = Path.Combine(filePath, fileName);
fileMode = IsFileHasData(path) ? fileMode : FileMode.CreateNew;
var fileAccess = fileMode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite;
using (FileStream nFile = new FileStream(path, fileMode, fileAccess, FileShare.ReadWrite, bufferSize))
{
using (StreamWriter sWriter = new StreamWriter(nFile, encoding))
{
//寫入數(shù)據(jù)
sWriter.Write(content);
return true;
}
}
}
catch (Exception ex)
{
Console.Write($"導(dǎo)出失敗: {ex.StackTrace}");
return false;
}
}
/// <summary>
/// 導(dǎo)出文本文件
/// </summary>
/// <param name="fileContent">文件內(nèi)容</param>
/// <param name="encoding">內(nèi)容編碼</param>
/// <param name="fileFullPath">文件保存路徑</param>
/// <returns>返回bool,true導(dǎo)出成功,false導(dǎo)出失敗</returns>
public static bool ExportFile(string content, Encoding encoding, string fileFullPath, FileMode fileMode = FileMode.Truncate)
{
try
{
var filePath = Path.GetDirectoryName(fileFullPath);
CreateFile(filePath);
fileMode = IsFileHasData(fileFullPath) ? fileMode : FileMode.CreateNew;
var fileAccess = fileMode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite;
using (FileStream nFile = new FileStream(fileFullPath, fileMode, fileAccess, FileShare.ReadWrite, bufferSize))
{
using (StreamWriter sWriter = new StreamWriter(nFile, encoding))
{
//寫入數(shù)據(jù)
sWriter.Write(content);
return true;
}
}
}
catch (Exception ex)
{
Console.Write($"導(dǎo)出失敗: {ex.StackTrace}");
return false;
}
}
/// <summary>
/// 導(dǎo)出文件
/// </summary>
/// <param name="fileContent">文件內(nèi)容</param>
/// <param name="filePath">文件保存路徑</param>
/// <param name="fileName">文件名以及后綴</param>
/// <param name="buffersiez">緩存區(qū)2048*2048=2m</param>
/// <returns>返回bool,true導(dǎo)出成功,false導(dǎo)出失敗</returns>
public static bool ExportFile(byte[] fileContent, string filePath, string fileName, FileMode fileMode = FileMode.Truncate)
{
try
{
CreateFile(filePath);
var path = Path.Combine(filePath, fileName);
fileMode = IsFileHasData(path) ? fileMode : FileMode.CreateNew;
var fileAccess = fileMode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite;
using (FileStream nFile = new FileStream(path, fileMode, fileAccess, FileShare.ReadWrite, bufferSize))
{
nFile.Write(fileContent, 0, fileContent.Length);
return true;
}
}
catch (Exception ex)
{
Console.Write($"導(dǎo)出失敗: {ex.StackTrace}");
return false;
}
}
/// <summary>
/// 導(dǎo)出文件
/// </summary>
/// <param name="fileContent">文件內(nèi)容</param>
/// <param name="filePath">文件保存路徑</param>
/// <param name="fileName">文件名以及后綴</param>
/// <param name="buffersiez">緩存區(qū)2048*2048=2m</param>
/// <returns>返回bool,true導(dǎo)出成功,false導(dǎo)出失敗</returns>
public static bool ExportFile(byte[] fileContent, string fileFullPath, FileMode fileMode = FileMode.Truncate)
{
try
{
var filePath = Path.GetDirectoryName(fileFullPath);
CreateFile(filePath);
fileMode = IsFileHasData(fileFullPath) ? fileMode : FileMode.CreateNew;
var fileAccess = fileMode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite;
using (FileStream nFile = new FileStream(fileFullPath, fileMode, fileAccess, FileShare.ReadWrite, bufferSize))
{
nFile.Write(fileContent, 0, fileContent.Length);
return true;
}
}
catch (Exception ex)
{
Console.Write($"導(dǎo)出失敗: {ex.StackTrace}");
return false;
}
}
/// <summary>
/// 獲取當(dāng)前設(shè)備的盤符
/// </summary>
/// <returns></returns>
public static List<string> GetDevicesPath()
{
var list = System.IO.Directory.GetLogicalDrives().ToList();
return list;
}
/// <summary>
/// 獲取文件夾內(nèi)所有文件夾路徑
/// </summary>
/// <param name="rootPath"></param>
/// <param name="searchOption"></param>
/// <returns></returns>
public static List<string> GetFoldersPath(string rootPath, SearchOption searchOption = SearchOption.AllDirectories)
{
List<string> foldersPath = new List<string>();
if (Directory.Exists(rootPath))
{
DirectoryInfo direction = new DirectoryInfo(rootPath);
var folders = direction.GetDirectories("*", searchOption);
foreach (var item in folders)
{
if (!foldersPath.Contains(item.FullName))
foldersPath.Add(item.FullName);
}
}
return foldersPath;
}
/// <summary>
/// 獲取文件夾下所有文件路徑
/// </summary>
/// <param name="fullPath">文件夾路徑</param>
/// <returns>字符串鏈表</returns>
public static List<string> GetFilesPath(string fullPath, SearchOption searchOption = SearchOption.AllDirectories)
{
List<string> filesPath = new List<string>();
//獲取指定路徑下面的所有資源文件 然后進(jìn)行刪除
if (Directory.Exists(fullPath))
{
DirectoryInfo direction = new DirectoryInfo(fullPath);
FileInfo[] files = direction.GetFiles("*", searchOption);
Console.Write(files.Length);
for (int i = 0; i < files.Length; i++)
{
filesPath.Add(files[i].FullName);
}
}
return filesPath;
}
/// <summary>
/// 獲取文件夾下指定類型文件路徑
/// </summary>
/// <param name="fullPath">文件夾路徑</param>
/// <param name="endswith">指定后綴的文件</param>
/// <returns>字符串鏈表</returns>
public static List<string> GetFilesPathEnd(string fullPath, List<string> endswith, SearchOption searchOption = SearchOption.AllDirectories)
{
List<string> filesPath = new List<string>();
//獲取指定路徑下面的所有資源文件 然后進(jìn)行刪除
if (Directory.Exists(fullPath))
{
DirectoryInfo direction = new DirectoryInfo(fullPath);
FileInfo[] files = direction.GetFiles("*", searchOption);
Console.Write(files.Length);
var endSwith = new List<string>();
endswith.ForEach(p => { var end = p.Replace(".", string.Empty); if (!endSwith.Contains(end)) endSwith.Add(end); });
for (int i = 0; i < files.Length; i++)
{
if (endswith.Contains(files[i].Extension.Replace(".", string.Empty)))
{
string FilePath = files[i].FullName;
filesPath.Add(FilePath);
}
}
}
return filesPath;
}
/// <summary>
/// 獲取文件夾下除指定類型外的所有文件路徑
/// </summary>
/// <param name="fullPath">文件夾路徑</param>
/// <param name="endswith">需要忽略的文件后綴</param>
/// <returns>字符串鏈表</returns>
public static List<string> GetFilesPathIgnoreEnd(string fullPath, List<string> IgnoreEndSwith, SearchOption searchOption = SearchOption.AllDirectories)
{
List<string> filesPath = new List<string>();
//獲取指定路徑下面的所有資源文件 然后進(jìn)行刪除
if (Directory.Exists(fullPath))
{
DirectoryInfo direction = new DirectoryInfo(fullPath);
FileInfo[] files = direction.GetFiles("*", searchOption);
Console.Write(files.Length);
var endSwith = new List<string>();
IgnoreEndSwith.ForEach(p => { var end = p.Replace(".", string.Empty); if (!endSwith.Contains(end)) endSwith.Add(end); });
for (int i = 0; i < files.Length; i++)
{
if (!endSwith.Contains(files[i].Extension.Replace(".", string.Empty)))
{
string FilePath = files[i].FullName;
filesPath.Add(FilePath);
}
}
}
return filesPath;
}
/// <summary>
/// 加載文件(返回byte數(shù)組)
/// </summary>
/// <param name="filePath">文件路徑</param>
/// <returns>返回byte數(shù)組</returns>
public static FileDataInfo LoadFile(string filePath)
{
FileDataInfo fileData = new FileDataInfo();
using (System.IO.FileStream fStream = new System.IO.FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, bufferSize))
{
byte[] fileBytes = new byte[fStream.Length];
fStream.Read(fileBytes, 0, fileBytes.Length);
fileData.Data = fileBytes;
fileData.FileFullPath = filePath;
return fileData;
}
}
/// <summary>
/// 加載多個(gè)文件(返回byte數(shù)組鏈表)
/// </summary>
/// <param name="filePath">文件路徑</param>
/// <returns>返回byte數(shù)組鏈表</returns>
public static List<FileDataInfo> LoadFiles(List<string> filesPath)
{
List<FileDataInfo> fileList = new List<FileDataInfo>();
for (int i = 0; i < filesPath.Count; i++)
{
fileList.Add(LoadFile(filesPath[i]));
}
return fileList;
}
/// <summary>
/// 讀取文件內(nèi)容(返回字符串)
/// </summary>
/// <param name="path"></param>
/// <returns>返回讀取內(nèi)容,如果文件不存在返回empty</returns>
public static FileDataInfo LoadFileContent(string path)
{
FileInfo file = new FileInfo(path);
FileDataInfo content = new FileDataInfo();
if (IsFileHasData(path))
{
Console.Write("未找到文件");
return content;
}
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, bufferSize))
{
using (StreamReader sr = new StreamReader(fs, Encoding.Default))
{
content.Content = sr.ReadToEnd();
content.FileFullPath = path;
}
}
return content;
}
/// <summary>
/// 刪除文件夾下指定后綴的文件
/// </summary>
/// <param name="fullPath">文件路徑</param>
/// <param name="endswith">需要?jiǎng)h除文件的后綴</param>
/// <returns>返回bool,true刪除成功,false刪除失敗</returns>
public static bool DeleteFileEnd(string fullPath, List<string> endswith, SearchOption searchOption=SearchOption.AllDirectories)
{
//獲取指定路徑下面的所有資源文件 然后進(jìn)行刪除
if (Directory.Exists(fullPath))
{
DirectoryInfo direction = new DirectoryInfo(fullPath);
FileInfo[] files = direction.GetFiles("*", searchOption);
Console.Write(files.Length);
var endSwith = new List<string>();
endswith.ForEach(p => { var end = p.Replace(".", string.Empty); if (!endSwith.Contains(end)) endSwith.Add(end); });
for (int i = 0; i < files.Length; i++)
{
if (endSwith.Contains(files[i].Extension.Replace(".", string.Empty)))
{
string FilePath = fullPath + "/" + files[i].Name;
File.Delete(FilePath);
}
}
return true;
}
return false;
}
/// <summary>
/// 刪除文件夾下除指定后綴的文件
/// </summary>
/// <param name="fullPath">文件路徑</param>
/// <param name="IgnoreEndswith">需要忽略的后綴</param>
/// <returns>返回bool,true刪除成功,false刪除失敗</returns>
public static bool DeleteFileIgnoreEnd(string fullPath, List<string> IgnoreEndswith, SearchOption searchOption = SearchOption.AllDirectories)
{
//獲取指定路徑下面的所有資源文件 然后進(jìn)行刪除
if (Directory.Exists(fullPath))
{
DirectoryInfo direction = new DirectoryInfo(fullPath);
FileInfo[] files = direction.GetFiles("*", searchOption);
Console.Write(files.Length);
var endSwith = new List<string>();
IgnoreEndswith.ForEach(p => { var end = p.Replace(".", string.Empty); if (!endSwith.Contains(end)) endSwith.Add(end); });
for (int i = 0; i < files.Length; i++)
{
if (endSwith.Contains(files[i].Extension.Replace(".", string.Empty)))
{
continue;
}
string FilePath = fullPath + "/" + files[i].Name;
File.Delete(FilePath);
}
return true;
}
return false;
}
/// <summary>
/// 刪除指定文件目錄下的所有文件
/// </summary>
/// <param name="fullPath">文件路徑</param>
/// <returns>返回bool,true刪除成功,false刪除失敗</returns>
public static bool DeleteAllFile(string fullPath, SearchOption searchOption = SearchOption.AllDirectories)
{
//獲取指定路徑下面的所有資源文件 然后進(jìn)行刪除
if (Directory.Exists(fullPath))
{
DirectoryInfo direction = new DirectoryInfo(fullPath);
FileInfo[] files = direction.GetFiles("*", searchOption);
Console.Write(files.Length);
for (int i = 0; i < files.Length; i++)
{
string FilePath = fullPath + "/" + files[i].Name;
File.Delete(FilePath);
}
return true;
}
return false;
}
/// <summary>
/// 刪除文件夾(包括文件夾中所有的子文件夾和子文件)
/// </summary>
/// <param name="folderPath"></param>
/// <param name="isDeleteRootFolder"></param>
/// <returns></returns>
public static bool DeleteFolder(string folderPath,bool isDeleteRootFolder=true)
{
if (Directory.Exists(folderPath))
{
var filesPath = GetFilesPath(folderPath);
foreach (var file in filesPath)
{
File.Delete(file);
}
var foldersPath = GetFoldersPath(folderPath);
foreach (var folder in foldersPath)
{
Directory.Delete(folder);
}
if (isDeleteRootFolder)
{
Directory.Delete(folderPath);
}
}
return false;
}
}
public class FileDataInfo
{
/// <summary>完整的文件路徑(絕對(duì)路徑)</summary>
public string FileFullPath=string.Empty;
/// <summary>完整的文件名(包含文件后綴)</summary>
public string FileFullName { get { return !string.IsNullOrEmpty(FileFullPath) ? Path.GetFileName(FileFullPath) : string.Empty; } }
/// <summary>文件名(不包含文件后綴)</summary>
public string FileName
{
get
{
if (!string.IsNullOrEmpty(FileFullName))
{
var content= FileFullName.Split('.');
if (content.Length > 1) { return content[0]; }
}
return string.Empty;
}
}
/// <summary>文件后綴</summary>
public string FileExtension
{
get
{
if(!string.IsNullOrEmpty(FileFullName))
{
var content= FileFullName.Split('.');
if (content.Length > 2) { return content[1]; }
}
return string.Empty;
}
}
/// <summary>文件數(shù)據(jù)</summary>
public byte[] Data=null;
/// <summary>文件大小</summary>
public ulong FileSize
{
get
{
return (ulong)(Data!=null? Data.Length : 0);
}
}
/// <summary>如果是文本文件的文件內(nèi)容</summary>
public string Content
{
get
{
if (Data != null && Data.Length > 0)
{
try
{
return Encoding.Default.GetString(Data);
}
catch (Exception ex)
{
Console.WriteLine($"代碼運(yùn)行錯(cuò)誤!Error={ex.StackTrace}");
return string.Empty;
}
}
return string.Empty;
}
set { Data = Encoding.Default.GetBytes(value);}
}
/// <summary>文件Base64內(nèi)容</summary>
public string Base64String
{
get
{
if (Data != null && Data.Length > 0)
{
try
{
return Convert.ToBase64String(Data);
}
catch (Exception ex)
{
Console.WriteLine($"代碼運(yùn)行錯(cuò)誤!Error={ex.StackTrace}");
return string.Empty;
}
}
return string.Empty;
}
set { Data = Convert.FromBase64String(value); }
}
}
到了這里,關(guān)于Unity C# 使用IO流對(duì)文件的常用操作的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!