forked from mchidk/BinaryRage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStorage.cs
94 lines (78 loc) · 2.23 KB
/
Storage.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
92
93
94
using System;
using System.Linq;
using System.IO;
using System.Threading;
using System.Collections.Generic;
namespace BinaryRage
{
internal static class Storage
{
private const string DB_EXTENTION = ".odb";
private static string createDirectoriesBasedOnKeyAndFilelocation(string key, string filelocation)
{
string pathSoFar = "";
foreach (var folder in GetFolders(key, filelocation))
{
try
{
pathSoFar = Path.Combine(pathSoFar, folder);
if (!Directory.Exists(pathSoFar))
Directory.CreateDirectory(pathSoFar);
}
catch (Exception)
{
}
}
return pathSoFar;
}
public static void WritetoStorage(string key, byte[] value, string filelocation)
{
//create folders
string dirstructure = createDirectoriesBasedOnKeyAndFilelocation(key, filelocation);
//Write the file to it's location
try
{
File.WriteAllBytes(CombinePathAndKey(dirstructure, key), value);
lock (Cache.LockObject)
{
//remove object from cache
Cache.CacheDic.Remove(filelocation + key);
}
}
catch (Exception)
{
}
Interlocked.Decrement(ref Cache.counter);
//Calculate pause based on amount of bytes
Thread.Sleep(value.Length / 100);
}
public static byte[] GetFromStorage(string key, string filelocation)
{
return File.ReadAllBytes(GetExactFileLocation(key, filelocation));
}
public static bool ExistingStorageCheck(string key, string filelocation)
{
return File.Exists(GetExactFileLocation(key, filelocation));
}
public static string GetExactFileLocation(string key, string filelocation)
{
return CombinePathAndKey(
path: Path.Combine(GetFolders(key, filelocation).ToArray()),
key: key);
}
public static byte[] GetFromStorageWithKnownFileLocation(string filelocation)
{
return File.ReadAllBytes(filelocation);
}
private static string CombinePathAndKey(string path, string key)
{
return Path.Combine(path, key + DB_EXTENTION);
}
private static IEnumerable<string> GetFolders(string key, string filelocation)
{
yield return filelocation;
foreach (var folder in Key.Splitkey(key))
yield return folder;
}
}
}