using System; using System.Collections.Generic; using System.IO; using Google.Protobuf.WellKnownTypes; using Sog; namespace FileTransDataObject { // 待发送的文件数据 public class FileData { public int FileSize => fileData == null ? 0 : fileData.Length; public string fileName; public string fileMd5; public byte[] fileData; public string readFilePath; // transNode上文件的读取路径 public string writeFilePath; // recvNode上文件的保存路径 public DateTime fileWriteTime; } // 文件传输节点: 负责监控recvNode的文件接收状态 public class FileTransNode { // 接收文件的host public string receiverHost; // 节点状态, -1 fail 0 trans 1 succ public int state; public long lastRecvMsgTime; // file name -> file state public List fileState; public FileTransNode() { fileState = new List(); } } public class FileUtils { public static FileData CreateFileData(string filePath, bool loadFile) { try { return CreateFileDataInner(filePath, loadFile); } catch (Exception e) { TraceLog.Exception(e); } return null; } private static FileData CreateFileDataInner(string filePath, bool loadFile) { byte[] fileData = null; string fileMd5; if (loadFile) { // 以共享模式ReadWrite打开, 避免文件被占用 using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { fileData = new byte[fs.Length]; fs.Read(fileData); fileMd5 = HashHelper.MD5Bytes(fileData); } } else { fileMd5 = HashHelper.MD5File(filePath); } // 文件不存在 if (string.IsNullOrEmpty(fileMd5)) { TraceLog.Error("FileUtils.CreateFileDataInner {0} not exist", filePath); return null; } var file = new FileData(); file.fileName = Path.GetFileName(filePath); file.fileData = fileData; file.fileMd5 = fileMd5; file.readFilePath = Path.GetDirectoryName(filePath); file.fileWriteTime = File.GetLastWriteTimeUtc(filePath); return file; } } }