-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathMethodExtensions.cs
More file actions
70 lines (63 loc) · 2.25 KB
/
Copy pathMethodExtensions.cs
File metadata and controls
70 lines (63 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace CodeGenerator.Utils
{
public static class MethodExtensions
{
/// <summary>
/// 递归遍历路径,得到所有文件
/// </summary>
/// <param name="path">路径一定是存在的,因为路径是系统Dialog返回的</param>
/// <param name="suffixes">后缀集合</param>
/// <returns></returns>
public static List<string> GetFilesBySuffix(this string path, HashSet<string> suffixes)
{
var result = new List<string>();
var directoryInfo = new DirectoryInfo(path);
foreach (var suffix in suffixes)
{
var files = directoryInfo.GetFiles($"{suffix}", SearchOption.AllDirectories);
result.AddRange(files.Select(file => file.FullName));
}
return result;
}
public static void TraverseFolder(this string path, ObservableCollection<FileInfo> result)
{
try
{
Parallel.ForEach(Directory.GetFiles(path), file => { result.Add(new FileInfo(file)); });
foreach (var dir in Directory.GetDirectories(path))
{
TraverseFolder(dir, result);
}
}
catch (Exception ex) when (ex is UnauthorizedAccessException || ex is IOException)
{
// 可选:记录无法访问的目录
Console.WriteLine($@"无法访问目录:{path},原因:{ex.Message}");
}
}
public static bool IsNumber(this string value)
{
return int.TryParse(value, out _);
}
/// <summary>
/// List 转 ObservableCollection
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
public static ObservableCollection<T> ToObservableCollection<T>(this List<T> list)
{
var collection = new ObservableCollection<T>();
foreach (var t in list)
{
collection.Add(t);
}
return collection;
}
}
}