| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114 |
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace Ips.Library.Basic
- {
- public static class FileUtil
- {
- public static bool DeleteIfExists(string filePath)
- {
- if (!File.Exists(filePath))
- {
- return false;
- }
- File.Delete(filePath);
- return true;
- }
- public static string GetExtension(string fileNameWithExtension)
- {
- var lastDotIndex = fileNameWithExtension.LastIndexOf('.');
- if (lastDotIndex < 0)
- {
- return null;
- }
- return fileNameWithExtension.Substring(lastDotIndex + 1);
- }
- public static async Task<string> ReadAllTextAsync(string path)
- {
- using (var reader = File.OpenText(path))
- {
- return await reader.ReadToEndAsync();
- }
- }
- public static async Task<byte[]> ReadAllBytesAsync(string path)
- {
- using (var stream = File.Open(path, FileMode.Open))
- {
- var result = new byte[stream.Length];
- await stream.ReadAsync(result, 0, (int)stream.Length);
- return result;
- }
- }
- public static async Task<string[]> ReadAllLinesAsync(string path,
- Encoding encoding = null,
- FileMode fileMode = FileMode.Open,
- FileAccess fileAccess = FileAccess.Read,
- FileShare fileShare = FileShare.Read,
- int bufferSize = 4096,
- FileOptions fileOptions = FileOptions.Asynchronous | FileOptions.SequentialScan)
- {
- if (encoding == null)
- {
- encoding = Encoding.UTF8;
- }
- var lines = new List<string>();
- using (var stream = new FileStream(
- path,
- fileMode,
- fileAccess,
- fileShare,
- bufferSize,
- fileOptions))
- {
- using (var reader = new StreamReader(stream, encoding))
- {
- string line;
- while ((line = await reader.ReadLineAsync()) != null)
- {
- lines.Add(line);
- }
- }
- }
- return lines.ToArray();
- }
- public static short[] ReadAllShorts(string file)
- {
- short[] result = null;
- using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
- {
- result = new short[fs.Length / 2];
- using (var reader = new BinaryReader(fs))
- {
- int i = 0;
- while (i < result.Length)
- {
- result[i++] = reader.ReadInt16();
- }
- }
- }
- return result;
- }
- public static void AppendToFileName(string val, ref string fileName)
- {
- if (fileName.IsNullOrWhitespace()) return;
- var dotIdx = fileName.LastIndexOf('.');
- var fileNameNoExt = fileName.Substring(0, dotIdx);
- var ext = fileName.Substring(dotIdx);
- fileName= fileNameNoExt + val + ext;
- }
- }
- }
|