IO流是C#语言中对文件操作常用的方式,但在Unity跨平台开发中需要注意有些平台不支持IO,有些平台的只读文件不支持支持操作,例如安卓平台的读取StreamingAsset文件夹等。
大部分项目中都会有大量的对文件操作需求,因此我使用IO流整理编写了一些常用的对文件操作方法,需要注意因为使用IO流操作,因此不支持读取远端文件,同时也不支持前面提及的某些平台或者某些路径中的文件操作不支持。
由于目前脚本中没有使用Unity特有的类,所以下面脚本在,单纯的C#项目中可以使用!
下面列举下该脚本中提供的方法,以及完整脚本(目前就这么多,后续会不断迭代更新,初步想法增加加载远端文件,以及加载一些不能用IO流加载的文件):
方法列表:
1、判断文件或文件夹是否存在
2、判断文件是否存在并且不为0字节
3、创建文件夹
4、删除文件
5、导出文件(可以是文本文件,包含多个重载)
6、获取设备所有盘符
7、获取文件夹下所有文件夹路径
8、获取文件夹下所有文件路径
9、获取文件夹下指定类型文件路径
10、获取文件夹下除指定类型外的所有文件路径
11、加载文件(可加载被其他进程打开的文件)
12、加载多个文件(可加载被其他进程打开的文件)
13、加载文本文件(可加载被其他进程打开的文件)
14、删除文件夹下指定后缀的文件
15、删除文件夹下除指定后缀的文件
16、删除指定文件目录下的所有文件
17、删除指定文件夹(包括文件夹内的子文件夹以及所有文件)文章来源:https://www.toymoban.com/news/detail-707610.html
代码如下:文章来源地址https://www.toymoban.com/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字节
/// </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($"代码运行错误!Error={ex.StackTrace}");
completed?.Invoke(false, null);
return false;
}
}
/// <summary>
/// 创建文件
/// </summary>
/// <param name="FilePath">文件路径</param>
/// <param name="IfHaveFileIsCreate">当文件存在时是否重新创建</param>
/// <returns>返回bool,true为创建成功,false没有创建</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>
/// 导出文本文件
/// </summary>
/// <param name="fileContent">文件内容</param>
/// <param name="filePath">文件保存路径</param>
/// <param name="fileName">文件名以及后缀</param>
/// <returns>返回bool,true导出成功,false导出失败</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))
{
//写入数据
sWriter.Write(content);
return true;
}
}
}
catch (Exception ex)
{
Console.Write($"导出失败: {ex.StackTrace}");
return false;
}
}
/// <summary>
/// 导出文本文件
/// </summary>
/// <param name="fileContent">文件内容</param>
/// <param name="fileFullPath">文件保存路径</param>
/// <returns>返回bool,true导出成功,false导出失败</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))
{
//写入数据
sWriter.Write(content);
return true;
}
}
}
catch (Exception ex)
{
Console.Write($"导出失败: {ex.StackTrace}");
return false;
}
}
/// <summary>
/// 导出文本文件
/// </summary>
/// <param name="fileContent">文件内容</param>
/// <param name="filePath">文件保存路径</param>
/// <param name="fileName">文件名以及后缀</param>
/// <returns>返回bool,true导出成功,false导出失败</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))
{
//写入数据
sWriter.Write(content);
return true;
}
}
}
catch (Exception ex)
{
Console.Write($"导出失败: {ex.StackTrace}");
return false;
}
}
/// <summary>
/// 导出文本文件
/// </summary>
/// <param name="fileContent">文件内容</param>
/// <param name="encoding">内容编码</param>
/// <param name="fileFullPath">文件保存路径</param>
/// <returns>返回bool,true导出成功,false导出失败</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))
{
//写入数据
sWriter.Write(content);
return true;
}
}
}
catch (Exception ex)
{
Console.Write($"导出失败: {ex.StackTrace}");
return false;
}
}
/// <summary>
/// 导出文件
/// </summary>
/// <param name="fileContent">文件内容</param>
/// <param name="filePath">文件保存路径</param>
/// <param name="fileName">文件名以及后缀</param>
/// <param name="buffersiez">缓存区2048*2048=2m</param>
/// <returns>返回bool,true导出成功,false导出失败</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($"导出失败: {ex.StackTrace}");
return false;
}
}
/// <summary>
/// 导出文件
/// </summary>
/// <param name="fileContent">文件内容</param>
/// <param name="filePath">文件保存路径</param>
/// <param name="fileName">文件名以及后缀</param>
/// <param name="buffersiez">缓存区2048*2048=2m</param>
/// <returns>返回bool,true导出成功,false导出失败</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($"导出失败: {ex.StackTrace}");
return false;
}
}
/// <summary>
/// 获取当前设备的盘符
/// </summary>
/// <returns></returns>
public static List<string> GetDevicesPath()
{
var list = System.IO.Directory.GetLogicalDrives().ToList();
return list;
}
/// <summary>
/// 获取文件夹内所有文件夹路径
/// </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>();
//获取指定路径下面的所有资源文件 然后进行删除
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>();
//获取指定路径下面的所有资源文件 然后进行删除
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>();
//获取指定路径下面的所有资源文件 然后进行删除
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数组)
/// </summary>
/// <param name="filePath">文件路径</param>
/// <returns>返回byte数组</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>
/// 加载多个文件(返回byte数组链表)
/// </summary>
/// <param name="filePath">文件路径</param>
/// <returns>返回byte数组链表</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>
/// 读取文件内容(返回字符串)
/// </summary>
/// <param name="path"></param>
/// <returns>返回读取内容,如果文件不存在返回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">需要删除文件的后缀</param>
/// <returns>返回bool,true删除成功,false删除失败</returns>
public static bool DeleteFileEnd(string fullPath, List<string> endswith, SearchOption searchOption=SearchOption.AllDirectories)
{
//获取指定路径下面的所有资源文件 然后进行删除
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)
{
//获取指定路径下面的所有资源文件 然后进行删除
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)
{
//获取指定路径下面的所有资源文件 然后进行删除
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>完整的文件路径(绝对路径)</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>文件数据</summary>
public byte[] Data=null;
/// <summary>文件大小</summary>
public ulong FileSize
{
get
{
return (ulong)(Data!=null? Data.Length : 0);
}
}
/// <summary>如果是文本文件的文件内容</summary>
public string Content
{
get
{
if (Data != null && Data.Length > 0)
{
try
{
return Encoding.Default.GetString(Data);
}
catch (Exception ex)
{
Console.WriteLine($"代码运行错误!Error={ex.StackTrace}");
return string.Empty;
}
}
return string.Empty;
}
set { Data = Encoding.Default.GetBytes(value);}
}
/// <summary>文件Base64内容</summary>
public string Base64String
{
get
{
if (Data != null && Data.Length > 0)
{
try
{
return Convert.ToBase64String(Data);
}
catch (Exception ex)
{
Console.WriteLine($"代码运行错误!Error={ex.StackTrace}");
return string.Empty;
}
}
return string.Empty;
}
set { Data = Convert.FromBase64String(value); }
}
}
到了这里,关于Unity C# 使用IO流对文件的常用操作的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!