-
-
Notifications
You must be signed in to change notification settings - Fork 254
/
LegalFilePathAttribute.cs
43 lines (38 loc) · 1.24 KB
/
LegalFilePathAttribute.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
// Copyright (c) Nate McMaster.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.ComponentModel.DataAnnotations;
using System.IO;
namespace McMaster.Extensions.CommandLineUtils
{
/// <summary>
/// Specifies that a value must be a legal file path.
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public sealed class LegalFilePathAttribute : ValidationAttribute
{
/// <summary>
/// Initializes an instance of <see cref="LegalFilePathAttribute"/>.
/// </summary>
public LegalFilePathAttribute()
: base("'{0}' is an invalid file path.")
{
}
/// <inheritdoc />
protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
{
if (value is string path)
{
try
{
var info = new FileInfo(path);
return ValidationResult.Success;
}
catch
{
}
}
return new ValidationResult(FormatErrorMessage(value?.ToString() ?? string.Empty));
}
}
}