forked from Taritsyn/JavaScriptEngineSwitcher
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileContentService.cs
More file actions
95 lines (85 loc) · 2.35 KB
/
FileContentService.cs
File metadata and controls
95 lines (85 loc) · 2.35 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
using System;
using System.IO;
#if NET451 || NET471 || NETSTANDARD
using Microsoft.AspNetCore.Hosting;
#elif NET40
using System.Web;
#else
#error No implementation for this target
#endif
using JavaScriptEngineSwitcher.Sample.Resources;
namespace JavaScriptEngineSwitcher.Sample.Logic.Services
{
public sealed class FileContentService
{
private readonly string _textContentDirectoryPath;
#if NET451 || NET471 || NETSTANDARD
private readonly IHostingEnvironment _hostingEnvironment;
#endif
#if NET451 || NET471 || NETSTANDARD
public FileContentService(
string textContentDirectoryPath,
IHostingEnvironment hostingEnvironment
)
{
_textContentDirectoryPath = textContentDirectoryPath;
_hostingEnvironment = hostingEnvironment;
}
#elif NET40
public FileContentService(string textContentDirectoryPath)
{
_textContentDirectoryPath = textContentDirectoryPath;
}
#else
#error No implementation for this target
#endif
public string GetFileContent(string filePath)
{
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentException(
string.Format(CommonStrings.ErrorMessage_FilePathNotSpecified, filePath),
"filePath"
);
}
string content;
string fullFilePath = _textContentDirectoryPath.TrimEnd('/') + "/" + filePath;
string physicalFilePath = GetPhysicalFilePath(fullFilePath);
try
{
using (FileStream fileStream = File.OpenRead(physicalFilePath))
using (var reader = new StreamReader(fileStream))
{
content = reader.ReadToEnd();
}
}
catch (FileNotFoundException)
{
throw new FileNotFoundException(
string.Format(CommonStrings.ErrorMessage_FileNotFound, filePath));
}
catch (DirectoryNotFoundException)
{
throw new FileNotFoundException(
string.Format(CommonStrings.ErrorMessage_FileNotFound, filePath));
}
return content;
}
private string GetPhysicalFilePath(string filePath)
{
#if NET451 || NET471 || NETSTANDARD
string applicationDirectoryPath = _hostingEnvironment.ContentRootPath;
#elif NET40
HttpContext context = HttpContext.Current;
string applicationDirectoryPath = context.Server.MapPath("~/");
#else
#error No implementation for this target
#endif
string physicalFilePath = Path.Combine(
applicationDirectoryPath,
filePath.Replace('/', '\\').TrimStart(new char[] { '\\' })
);
return physicalFilePath;
}
}
}