-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathFileDialogFilterStringBuilder.cs
More file actions
123 lines (71 loc) · 2.97 KB
/
FileDialogFilterStringBuilder.cs
File metadata and controls
123 lines (71 loc) · 2.97 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
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
123
using Gsemac.IO.FileFormats;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Gsemac.IO {
public sealed class FileDialogFilterStringBuilder :
IFileDialogFilterStringBuilder {
// Public members
public IFileDialogFilterStringBuilder WithFileFormat(IFileFormat format) {
if (format is null)
throw new ArgumentNullException(nameof(format));
if (format.Equals(FileFormat.Any)) {
showAllFilesOption = true;
}
else {
return WithFileFormat(format.Name, format.Extensions);
}
return this;
}
public IFileDialogFilterStringBuilder WithFileFormat(string name, string extension) {
if (string.IsNullOrWhiteSpace(name))
return this;
return WithFileFormat(name, new[] { extension });
}
public IFileDialogFilterStringBuilder WithFileFormat(string name, IEnumerable<string> extensions) {
if (extensions is null)
throw new ArgumentNullException(nameof(extensions));
if (string.IsNullOrWhiteSpace(name))
return this;
string formattedName = FormatFileFormatName(name);
string formattedFileExtensions = string.Join(";", extensions.Select(ext => FormatFileFormatExtension(ext)));
formats.Add($"{formattedName} ({formattedFileExtensions})|({formattedFileExtensions})");
return this;
}
public IFileDialogFilterStringBuilder WithAllFilesOption() {
showAllFilesOption = true;
return this;
}
public string Build() {
StringBuilder sb = new StringBuilder();
sb.Append(string.Join("|", formats.Distinct()));
if (showAllFilesOption)
sb.Append("|All Files (*.*)|*.*");
return sb.ToString();
}
public override string ToString() {
return Build();
}
// Private members
private readonly List<string> formats = new List<string>();
private bool showAllFilesOption = false;
private string FormatFileFormatName(string name) {
// File dialog filters, in practice, tend to use title case for the file format names.
// The name should be plural.
if (string.IsNullOrWhiteSpace(name))
return name;
if (!name.EndsWith("s", StringComparison.OrdinalIgnoreCase))
name += "s";
return name;
}
private string FormatFileFormatExtension(string extension) {
// File extensions should be lowercase and begin with a wildcard character.
if (string.IsNullOrWhiteSpace(extension))
return extension;
extension = extension.TrimStart('*', '.')
.ToLowerInvariant();
return $"*.{extension}";
}
}
}