-
Notifications
You must be signed in to change notification settings - Fork 11
/
FileHelper.cs
91 lines (74 loc) · 2.41 KB
/
FileHelper.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
using Microsoft.AspNetCore.Http;
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using Core.Utilities.Results;
namespace Core.Utilities.Helpers
{
public class FileHelper
{
public static string AddAsync(IFormFile file)
{
var result = newPath(file);
try
{
var sourcepath = Path.GetTempFileName();
if (file.Length > 0)
using (var stream = new FileStream(sourcepath, FileMode.Create))
file.CopyTo(stream);
File.Move(sourcepath, result.newPath);
}
catch (Exception exception)
{
return exception.Message;
}
return result.Path2.Replace("\\", "/");
}
public static string UpdateAsync(string sourcePath, IFormFile file)
{
var result = newPath(file);
try
{
//File.Copy(sourcePath,result);
if (sourcePath.Length > 0)
{
using (var stream = new FileStream(result.newPath, FileMode.Create))
{
file.CopyTo(stream);
}
}
File.Delete(sourcePath);
}
catch (Exception excepiton)
{
return excepiton.Message;
}
return result.Path2.Replace("\\","/");
}
public static IResult DeleteAsync(string path)
{
try
{
File.Delete(path);
}
catch (Exception exception)
{
return new ErrorResult(exception.Message);
}
return new SuccessResult();
}
public static (string newPath, string Path2) newPath(IFormFile file)
{
FileInfo ff = new FileInfo(file.FileName);
string fileExtension = ff.Extension;
var creatingUniqueFilename = Guid.NewGuid().ToString("N")
+ "_" + DateTime.Now.Month + "_"
+ DateTime.Now.Day + "_"
+ DateTime.Now.Year + fileExtension;
string path = Environment.CurrentDirectory + @"\wwwroot\Images";
string result = $@"{path}\{creatingUniqueFilename}";
return (result, $"\\Images\\{creatingUniqueFilename}");
}
}
}