-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSftpFileAccess.cs
447 lines (324 loc) · 17.3 KB
/
SftpFileAccess.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
using System.Text;
using System.Text.RegularExpressions;
using Infra.Core.Extensions;
using Infra.Core.FileAccess.Abstractions;
using Infra.Core.FileAccess.Enums;
using Infra.Core.FileAccess.Models;
using Infra.FileAccess.Sftp.Configuration;
using Infra.FileAccess.Sftp.Configuration.Validators;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Renci.SshNet;
using Renci.SshNet.Sftp;
namespace Infra.FileAccess.Sftp;
public class SftpFileAccess : IFileAccess
{
private readonly ILogger<SftpFileAccess> logger;
private readonly Settings settings;
public SftpFileAccess(ILogger<SftpFileAccess> logger, IOptions<Settings> settings)
{
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
this.settings = SettingsValidator.TryValidate(settings.Value, out var validationException) ? settings.Value : throw validationException;
}
#region Sync Method
#region Directory
public void CreateDirectory(string directoryPath) => throw new NotSupportedException();
public bool DirectoryExists(string directoryPath) => throw new NotSupportedException();
public string[] GetFiles(string directoryPath, string searchPattern = "", SearchOption searchOption = default) => throw new NotSupportedException();
public void DeleteDirectory(string directoryPath, bool recursive = true) => throw new NotSupportedException();
public string[] GetSubDirectories(string directoryPath, string searchPattern = "", SearchOption searchOption = default) => throw new NotSupportedException();
public void DirectoryCompress(string directoryPath, string zipFilePath, int compressionLevel = 6) => throw new NotSupportedException();
public void DirectorySplitCompress(string directoryPath, string zipFilePath, ZipDataUnit zipDataUnit, int segmentSize, int compressionLevel = 6) => throw new NotSupportedException();
public string GetParentPath(string directoryPath) => throw new NotSupportedException();
public string GetCurrentDirectoryName(string directoryPath) => throw new NotSupportedException();
#endregion
public bool FileExists(string filePath) => throw new NotSupportedException();
public void SaveFile(string filePath, string content) => throw new NotSupportedException();
public void SaveFile(string filePath, string content, Encoding encoding) => throw new NotSupportedException();
public void SaveFile(string filePath, byte[] bytes) => throw new NotSupportedException();
public void DeleteFile(string filePath) => throw new NotSupportedException();
public long GetFileSize(string filePath) => throw new NotSupportedException();
public string ReadTextFile(string filePath) => throw new NotSupportedException();
public string ReadTextFile(string filePath, Encoding encoding) => throw new NotSupportedException();
public byte[] ReadFile(string filePath) => throw new NotSupportedException();
public void MoveFile(string sourceFilePath, string destFilePath, bool overwrite = true) => throw new NotSupportedException();
public void CopyFile(string sourceFilePath, string destFilePath, bool overwrite = true) => throw new NotSupportedException();
public void AppendAllLines(string filePath, IEnumerable<string> contents) => throw new NotSupportedException();
public void AppendAllLines(string filePath, IEnumerable<string> contents, Encoding encoding) => throw new NotSupportedException();
public string[] ReadAllLines(string filePath) => throw new NotSupportedException();
public string[] ReadAllLines(string filePath, Encoding encoding) => throw new NotSupportedException();
public void AppendAllText(string filePath, string content) => throw new NotSupportedException();
public void AppendAllText(string filePath, string content, Encoding encoding) => throw new NotSupportedException();
public void CompressFiles(Dictionary<string, string> files, string zipFilePath, int compressionLevel = 6) => throw new NotSupportedException();
public void CompressFiles(Dictionary<string, byte[]> files, string zipFilePath, int compressionLevel = 6) => throw new NotSupportedException();
public byte[] CompressFiles(Dictionary<string, string> files, int compressionLevel = 6) => throw new NotSupportedException();
public byte[] CompressFiles(Dictionary<string, byte[]> files, int compressionLevel = 6) => throw new NotSupportedException();
#endregion
#region Async Method
#region Directory
public Task CreateDirectoryAsync(string directoryPath, Action<ProgressInfo> progressCallBack = null, CancellationToken cancellationToken = default)
{
using var sftp = GetSftpClient();
try
{
sftp.Connect();
sftp.CreateDirectory(GetRegularPath(directoryPath));
}
catch (Exception ex)
{
logger.Error($"Create sftp directory error: {ex.Message}");
throw;
}
finally
{
sftp.Disconnect();
}
return Task.CompletedTask;
}
public Task<bool> DirectoryExistsAsync(string directoryPath, Action<ProgressInfo> progressCallBack = null, CancellationToken cancellationToken = default)
{
using var sftp = GetSftpClient();
try
{
sftp.Connect();
return Task.FromResult(sftp.Exists(GetRegularPath(directoryPath)));
}
catch (Exception ex)
{
logger.Error($"Check sftp directory exists error: {ex.Message}");
throw;
}
finally
{
sftp.Disconnect();
}
}
public Task<string[]> GetFilesAsync(string directoryPath, string searchPattern = "", SearchOption searchOption = default, Action<ProgressInfo> progressCallBack = null, CancellationToken cancellationToken = default)
{
var sftpFiles = GetSftpFiles(directoryPath, searchPattern, searchOption);
return Task.FromResult(sftpFiles.Where(sftpFile => !sftpFile.IsDirectory).Select(item => item.FullName).ToArray());
}
public Task DeleteDirectoryAsync(string directoryPath, bool recursive = true, Action<ProgressInfo> progressCallBack = null, CancellationToken cancellationToken = default)
{
using var sftp = GetSftpClient();
try
{
sftp.Connect();
directoryPath = GetRegularPath(directoryPath);
foreach (var sftpFile in sftp.ListDirectory(directoryPath).Where(sftpFile => sftpFile.Name != "." && sftpFile.Name != ".."))
{
if (sftpFile.IsDirectory)
DeleteDirectoryAsync(sftpFile.FullName, recursive, progressCallBack, cancellationToken);
else
sftp.DeleteFile(sftpFile.FullName);
}
sftp.DeleteDirectory(directoryPath);
}
catch (Exception ex)
{
logger.Error($"Delete sftp directory error: {ex.Message}");
throw;
}
finally
{
sftp.Disconnect();
}
return Task.CompletedTask;
}
public Task<string[]> GetSubDirectoriesAsync(string directoryPath, string searchPattern = "", SearchOption searchOption = default, Action<ProgressInfo> progressCallBack = null, CancellationToken cancellationToken = default)
{
var sftpFiles = GetSftpFiles(directoryPath, searchPattern, searchOption);
return Task.FromResult(sftpFiles.Where(sftpFile => sftpFile.IsDirectory).Select(item => item.FullName).ToArray());
}
public Task DirectoryCompressAsync(string directoryPath, string zipFilePath, int compressionLevel = 6, Action<ProgressInfo> progressCallBack = null, CancellationToken cancellationToken = default) => throw new NotSupportedException();
public Task DirectorySplitCompressAsync(string directoryPath, string zipFilePath, ZipDataUnit zipDataUnit, int segmentSize, int compressionLevel = 6, Action<ProgressInfo> progressCallBack = null, CancellationToken cancellationToken = default) => throw new NotSupportedException();
public Task<string> GetParentPathAsync(string directoryPath, Action<ProgressInfo> progressCallBack = null, CancellationToken cancellationToken = default) => throw new NotSupportedException();
public Task<string> GetCurrentDirectoryNameAsync(string directoryPath, Action<ProgressInfo> progressCallBack = null, CancellationToken cancellationToken = default) => throw new NotSupportedException();
#endregion
public Task<bool> FileExistsAsync(string filePath, Action<ProgressInfo> progressCallBack = null, CancellationToken cancellationToken = default)
{
using var sftp = GetSftpClient();
try
{
sftp.Connect();
return Task.FromResult(sftp.Exists(GetRegularPath(filePath)));
}
catch (Exception ex)
{
logger.Error($"Check sftp file exists error: {ex.Message}");
throw;
}
finally
{
sftp.Disconnect();
}
}
public async Task SaveFileAsync(string filePath, string content, Action<ProgressInfo> progressCallBack = null, CancellationToken cancellationToken = default)
=> await SaveFileAsync(filePath, content, Encoding.UTF8, progressCallBack, cancellationToken);
public async Task SaveFileAsync(string filePath, string content, Encoding encoding, Action<ProgressInfo> progressCallBack = null, CancellationToken cancellationToken = default)
{
var contentBytes = encoding.GetBytes(content);
await SaveFileAsync(filePath, contentBytes, progressCallBack, cancellationToken);
}
public Task SaveFileAsync(string filePath, byte[] bytes, Action<ProgressInfo> progressCallBack = null, CancellationToken cancellationToken = default)
{
using var sftp = GetSftpClient();
try
{
sftp.Connect();
sftp.UploadFile(new MemoryStream(bytes), GetRegularPath(filePath));
}
catch (Exception ex)
{
logger.Error($"Upload file to sftp error: {ex.Message}");
throw;
}
finally
{
sftp.Disconnect();
}
return Task.CompletedTask;
}
public Task DeleteFileAsync(string filePath, Action<ProgressInfo> progressCallBack = null, CancellationToken cancellationToken = default)
{
using var sftp = GetSftpClient();
try
{
sftp.Connect();
sftp.DeleteFile(GetRegularPath(filePath));
}
catch (Exception ex)
{
logger.Error($"Delete sftp file error: {ex.Message}");
throw;
}
finally
{
sftp.Disconnect();
}
return Task.CompletedTask;
}
public Task<long> GetFileSizeAsync(string filePath, Action<ProgressInfo> progressCallBack = null, CancellationToken cancellationToken = default)
{
using var sftp = GetSftpClient();
try
{
sftp.Connect();
return Task.FromResult(sftp.Get(GetRegularPath(filePath)).Attributes.Size);
}
catch (Exception ex)
{
logger.Error($"Get sftp file size error: {ex.Message}");
throw;
}
finally
{
sftp.Disconnect();
}
}
public async Task<string> ReadTextFileAsync(string filePath, Action<ProgressInfo> progressCallBack = null, CancellationToken cancellationToken = default)
=> await ReadTextFileAsync(filePath, Encoding.UTF8, progressCallBack, cancellationToken);
public async Task<string> ReadTextFileAsync(string filePath, Encoding encoding, Action<ProgressInfo> progressCallBack = null, CancellationToken cancellationToken = default)
{
var fileBytes = await ReadFileAsync(filePath, progressCallBack, cancellationToken);
using var stream = new StreamReader(new MemoryStream(fileBytes), encoding);
return await stream.ReadToEndAsync(cancellationToken);
}
public Task<byte[]> ReadFileAsync(string filePath, Action<ProgressInfo> progressCallBack = null, CancellationToken cancellationToken = default)
{
using var sftp = GetSftpClient();
try
{
sftp.Connect();
using var ms = new MemoryStream();
sftp.DownloadFile(GetRegularPath(filePath), ms);
return Task.FromResult(ms.ToArray());
}
catch (Exception ex)
{
logger.Error($"Download file from sftp error: {ex.Message}");
throw;
}
finally
{
sftp.Disconnect();
}
}
public async Task MoveFileAsync(string sourceFilePath, string destFilePath, bool overwrite = true, Action<ProgressInfo> progressCallBack = null, CancellationToken cancellationToken = default)
{
try
{
await CopyFileAsync(sourceFilePath, destFilePath, overwrite, progressCallBack, cancellationToken);
await DeleteFileAsync(sourceFilePath, progressCallBack, cancellationToken);
}
catch (Exception ex)
{
logger.Error($"Move sftp file error: {ex.Message}");
throw;
}
}
public async Task CopyFileAsync(string sourceFilePath, string destFilePath, bool overwrite = true, Action<ProgressInfo> progressCallBack = null, CancellationToken cancellationToken = default)
{
try
{
var bytes = await ReadFileAsync(sourceFilePath, progressCallBack, cancellationToken);
await SaveFileAsync(destFilePath, bytes, progressCallBack, cancellationToken);
}
catch (Exception ex)
{
logger.Error($"Copy sftp file error: {ex.Message}");
throw;
}
}
public Task AppendAllLinesAsync(string filePath, IEnumerable<string> contents, Action<ProgressInfo> progressCallBack = null, CancellationToken cancellationToken = default) => throw new NotSupportedException();
public Task AppendAllLinesAsync(string filePath, IEnumerable<string> contents, Encoding encoding, Action<ProgressInfo> progressCallBack = null, CancellationToken cancellationToken = default) => throw new NotSupportedException();
public Task<string[]> ReadAllLinesAsync(string filePath, Action<ProgressInfo> progressCallBack = null, CancellationToken cancellationToken = default) => throw new NotSupportedException();
public Task<string[]> ReadAllLinesAsync(string filePath, Encoding encoding, Action<ProgressInfo> progressCallBack = null, CancellationToken cancellationToken = default) => throw new NotSupportedException();
public Task AppendAllTextAsync(string filePath, string content, Action<ProgressInfo> progressCallBack = null, CancellationToken cancellationToken = default) => throw new NotSupportedException();
public Task AppendAllTextAsync(string filePath, string content, Encoding encoding, Action<ProgressInfo> progressCallBack = null, CancellationToken cancellationToken = default) => throw new NotSupportedException();
public Task CompressFilesAsync(Dictionary<string, string> files, string zipFilePath, int compressionLevel = 6, Action<ProgressInfo> progressCallBack = null, CancellationToken cancellationToken = default) => throw new NotSupportedException();
public Task CompressFilesAsync(Dictionary<string, byte[]> files, string zipFilePath, int compressionLevel = 6, Action<ProgressInfo> progressCallBack = null, CancellationToken cancellationToken = default) => throw new NotSupportedException();
public Task<byte[]> CompressFilesAsync(Dictionary<string, string> files, int compressionLevel = 6, Action<ProgressInfo> progressCallBack = null, CancellationToken cancellationToken = default) => throw new NotSupportedException();
public Task<byte[]> CompressFilesAsync(Dictionary<string, byte[]> files, int compressionLevel = 6, Action<ProgressInfo> progressCallBack = null, CancellationToken cancellationToken = default) => throw new NotSupportedException();
#endregion
#region Private Method
/// <summary>
/// 取得 SFTP 清單項目
/// </summary>
/// <param name="path">路徑</param>
/// <param name="searchPattern">搜尋 Pattern</param>
/// <param name="searchOption">搜尋選項</param>
/// <returns></returns>
private IEnumerable<ISftpFile> GetSftpFiles(string path, string searchPattern, SearchOption searchOption)
{
var sftpFiles = new List<ISftpFile>();
using var sftp = GetSftpClient();
try
{
sftp.Connect();
foreach (var sftpFile in sftp.ListDirectory(GetRegularPath(path)).Where(sftpFile => sftpFile.Name != "." && sftpFile.Name != ".."))
{
if (sftpFile.IsDirectory && searchOption is SearchOption.AllDirectories) sftpFiles.AddRange(GetSftpFiles(sftpFile.FullName, searchPattern, searchOption));
sftpFiles.Add(sftpFile);
}
var regex = new Regex(searchPattern);
return sftpFiles.Where(sftpFile => regex.IsMatch(sftpFile.Name));
}
finally
{
sftp.Disconnect();
}
}
/// <summary>
/// 取得 SftpClient
/// </summary>
/// <returns></returns>
private SftpClient GetSftpClient() => new(settings.Host, settings.Port, settings.User, settings.Password);
/// <summary>
/// 取得常規的路徑
/// </summary>
/// <param name="path">路徑</param>
/// <returns></returns>
private static string GetRegularPath(string path) => path.Replace("\\", "/");
#endregion
}