-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileList.cs
122 lines (110 loc) · 3.48 KB
/
FileList.cs
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace RandomFiles
{
class FileList
{
List<FileItem> files;
string sourcePath;
public FileList(string sourceFolder)
{
sourcePath = sourceFolder;
files = new List<FileItem>();
}
public void LoadFilesList(string[] types)
{
files = new List<FileItem>();
if (!Directory.Exists(sourcePath))
{
throw new DirectoryNotFoundException(
"The source destination does not exist.");
}
GetChildren(sourcePath, types);
if (files.Count < 1)
{
throw new Exception("No files in the source!");
}
}
/// <summary>
/// Fills the "files" with the files of a folder with search pattern.
/// </summary>
/// <param name="dir"></param>
/// <param name="pattern"></param>
private void GetFilesOfDir(string dir, string pattern)
{
foreach (string f in Directory.GetFiles(
dir, pattern, SearchOption.AllDirectories))
{
var info = new FileInfo(f);
files.Add(new FileItem
{
Path = f,
Size = info.Length
});
}
}
/// <summary>
/// Fills the "files" of the given directory.
/// </summary>
/// <param name="dir"></param>
/// <param name="types">Some file exts like mp3, jpg, etc.</param>
private void GetChildren(string dir, string[] types)
{
try
{
if (types.Length > 0)
{
foreach (var type in types)
{
GetFilesOfDir(dir, $"*.{type}");
}
}
else
{
GetFilesOfDir(dir, "");
}
}
catch { }
}
/// <summary>
/// Gets a list of files randomly.
/// The total size of the generated list will less than
/// or equal to the size.
/// </summary>
/// <param name="size">Size of the generated list in MB</param>
/// <returns></returns>
public List<FileItem> GetRandomFileList(long size = 1024)
{
var selectedFiles = new List<FileItem>();
if (files.Count < 1)
{
throw new Exception("No file is selected.");
}
var random = new Random();
long totalSelectedSize = 0;
var maxSize = size * 1048576; // to change it to bytes
var maxTries = files.Count;
var tries = 0;
while (selectedFiles.Count < files.Count &&
totalSelectedSize <= maxSize &&
tries <= maxTries)
{
int itemIndex = random.Next(files.Count);
FileItem item = files[itemIndex];
if (selectedFiles.Any(i => i.Path == item.Path))
{
continue;
}
tries++;
if ((totalSelectedSize + item.Size) <= maxSize)
{
selectedFiles.Add(item);
totalSelectedSize += item.Size;
}
}
return selectedFiles;
}
}
}