-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathFileHelper.cs
More file actions
94 lines (89 loc) · 3.2 KB
/
FileHelper.cs
File metadata and controls
94 lines (89 loc) · 3.2 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
using System.IO;
using System.Text;
namespace FileMonitor
{
public static class FileHelper
{
/// <summary>
/// 覆写
/// </summary>
/// <param name="path"></param>
/// <param name="data"></param>
public static void Write(this string[] path, string data)
{
string pathStr = Path.Combine(path);
string dicPath = string.Empty;
if (path.Length > 1)
dicPath = Path.Combine(path.GetByCount(0, path.Length - 1));
if (!string.IsNullOrEmpty(dicPath) && !Directory.Exists(dicPath))
Directory.CreateDirectory(dicPath);
using (FileStream fileStream = new FileStream(pathStr, FileMode.Create))
{
byte[] bytes = Encoding.UTF8.GetBytes(data);
fileStream.Write(bytes, 0, bytes.Length);
};
}
/// <summary>
/// 读取
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string Read(this string[] path)
{
string pathStr = Path.Combine(path);
if (!File.Exists(pathStr))
return string.Empty;
using (FileStream fileStream = new FileStream(pathStr, FileMode.Open))
{
int length = (int)fileStream.Length;
byte[] bytes = new byte[length];
fileStream.Read(bytes, 0, bytes.Length);
return Encoding.UTF8.GetString(bytes);
};
}
public static byte[] ReadStream(string path)
{
using (FileStream fileStream = new FileStream(path, FileMode.Open))
{
int length = (int)fileStream.Length;
byte[] bytes = new byte[length];
fileStream.Read(bytes, 0, bytes.Length);
return bytes;
};
}
/// <summary>
/// 续写
/// </summary>
/// <param name="path"></param>
/// <param name="data"></param>
public static void Write_Append(this string[] path, string data)
{
string pathStr = Path.Combine(path);
string dicPath = string.Empty;
if (path.Length > 1)
dicPath = Path.Combine(path.GetByCount(0, path.Length - 1));
if (!string.IsNullOrEmpty(dicPath) && !Directory.Exists(dicPath))
Directory.CreateDirectory(dicPath);
using (FileStream fileStream = new FileStream(pathStr, FileMode.Append))
{
byte[] bytes = Encoding.UTF8.GetBytes(data);
fileStream.Write(bytes, 0, bytes.Length);
};
}
/// <summary>
/// 获取字符串数组的指定数量的子集
/// </summary>
/// <param name="data"></param>
/// <param name="count"></param>
/// <returns></returns>
private static string[] GetByCount(this string[] data, int offset, int count)
{
string[] result = new string[count - offset];
for (int i = offset; i < count; i++)
{
result[i - offset] = data[i];
}
return result;
}
}
}