-
Notifications
You must be signed in to change notification settings - Fork 0
/
FileManager.cs
69 lines (60 loc) · 1.94 KB
/
FileManager.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
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace ShareMe
{
public static class FileManager
{
public async static Task<string> WriteFile(string fileExtension, IFormFile file, string physicalUploadPath)
{
EnsureDirectory(physicalUploadPath);
// Generate a file name, keep going if you get a collision with an existing file
string fileName = string.Empty;
do
{
fileName = $"{RandomGenerator.GetRandomString(7)}.{fileExtension}";
} while (File.Exists(Path.Combine(physicalUploadPath, $"{fileName}.{fileExtension}")));
try
{
string systemFilePath = Path.Combine(physicalUploadPath, fileName);
using (var stream = File.Create(systemFilePath))
{
await file.CopyToAsync(stream);
}
return fileName;
}
catch (Exception)
{
throw;
}
}
// Deletes a file, null for exception, true for deleted, false for not existing
public static bool? DeleteFile(string filename, string physicalUploadPath)
{
EnsureDirectory(physicalUploadPath);
try
{
if (File.Exists(Path.Combine(physicalUploadPath, filename)))
{
File.Delete(Path.Combine(physicalUploadPath, filename));
return true;
}
else
{
return false;
}
}
catch (Exception)
{
return null;
}
}
public static void EnsureDirectory(string uploadFolder)
{
Directory.CreateDirectory(uploadFolder);
}
}
}