持续更新中...
1. string转枚举
public static class StringExtensions
{
public static T ToEnum<T>(this string str)
{
try
{
return (T)Enum.Parse(typeof(T), str);
}
catch
{
return default;
}
}
}
示例代码
string value = "Monday";
DayOfWeek day = value.ToEnum<DayOfWeek>();
2. 移除所有非汉字、字母、数字的字符
public static string RemoveTitleSymbol(this string str)
{
return Regex.Replace(str, @"[^\u4e00-\u9fa5a-zA-Z0-9]", "");
}
示例代码
string originalString = "这是 一段 含有 宫格 的 字符串,123!@#";
string filteredString = originalString.RemoveTitleSymbol();
3. 移除空格
public static string RemoveSpace(this string str)
{
return Regex.Replace(str, @"\s", "");
}
示例代码
string originalString = "这是 一段 含有 宫格 的 字符串";
string filteredString = originalString.RemoveSpace();
4.判断文件是否存在
public static bool IsFileExist(this string path)
{
// 判断文件路径是否为空或空白字符串
if (string.IsNullOrWhiteSpace(path))
{
throw new ArgumentException("File path is null or empty.");
}
return System.IO.File.Exists(path);
}
示例代码
string filePath = "C:/example/file.txt";
bool fileExist = filePath.IsFileExist();
Debug.Log(fileExist);
5.根据路径创建文件夹
public static void CreateFolder(this string path)
{
// 判断文件夹路径是否为空或空白字符串
if (string.IsNullOrWhiteSpace(path))
{
throw new ArgumentException("Folder path is null or empty.");
}
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
}
}
示例代码
string folderPath = "C:/example/folder";
folderPath.CreateFolder();
6.URL中提取文件名
public static string ExtractFileNameFromUrl(this string url)
{
if (string.IsNullOrEmpty(url))
return string.Empty;
if (Uri.TryCreate(url, UriKind.Absolute, out var uri))
{
// 提取路径部分
string path = uri.AbsolutePath;
// 获取最后一个斜杠后的字符串,即文件名
int lastSlashIndex = path.LastIndexOf('/');
if (lastSlashIndex >= 0 && lastSlashIndex < path.Length - 1)
{
return path.Substring(lastSlashIndex + 1);
}
}
return string.Empty;
}
示例代码
string downloadUrl = "http://example.com/file.zip";
var fileName = downloadUrl.ExtractFileNameFromUrl();