public FileManager() { var superBlock = new SuperBlock(1, Directory.GetCurrentDirectory() + "/dir"); var hash = Encoding.UTF8.GetBytes("testtesttesttesttest"); BlockIndex index = new BlockIndex(0, Encoding.UTF8.GetBytes("test"), hash, 3, 2, 1); var index2 = new BlockIndex(index.ToHeaderBytes()); Block block = new Block(index.ToHeaderBytes(), "app", 4); Block block2 = new Block(new MemoryStream(block.ToBytes(hash))); this.superBlocks.Add(1, superBlock); }
public void AddFile(string dir, string fileName, Stream stream) { var path = string.Join("/", dir.Split('\\', '/').Skip(1).ToArray()); //得到文件的数据 byte[] dataBytes = GetCompressedData(stream); //得到文件的名称 var filePath = Encoding.UTF8.GetBytes(path + "/" + fileName); //得到文件的哈希 var hash = sha(dataBytes); //判断文件内容是否已经存在 if (fileDataIndex.ContainsKey(hash)) { //判断文件名称是否已经存在 if (!fileNameIndex.ContainsKey(filePath)) { fileNameIndex.Add(filePath, fileDataIndex[hash]); } else { fileNameIndex[filePath] = fileDataIndex[hash]; } return; } var blockIndex = new BlockIndex((uint)(dataFileWriter.Position / 8), filePath, hash); this.fileBlocks.Add(blockIndex); var fileIndex = this.fileBlocks.Count - 1; fileDataIndex.Add(hash, fileIndex); //判断文件名称是否已经存在 if (!fileNameIndex.ContainsKey(filePath)) { fileNameIndex.Add(filePath, fileDataIndex[hash]); } else { fileNameIndex[filePath] = fileDataIndex[hash]; } Block block = new Block(blockIndex.ToHeaderBytes(), "", 0); dataBytes = block.ToBytes(dataBytes); dataFileWriter.Write(dataBytes, 0, dataBytes.Length); dataFileWriter.Flush(); }
public SuperBlock(uint volumeId, string root) { this.VolumeId = volumeId; this.dataFile = Path.Combine(root, this.VolumeId + ".data"); this.indexFile = Path.Combine(root, this.VolumeId + ".index"); this.dataFileWriter = File.Open(this.dataFile, FileMode.OpenOrCreate, FileAccess.ReadWrite); using (var indexFileReader = File.Open(this.indexFile, FileMode.OpenOrCreate, FileAccess.Read)) { byte[] buffer = new byte[4]; indexFileReader.Read(buffer, 0, 4); int size = BitConverter.ToInt32(buffer, 0); while (size > 0) { buffer = new byte[size]; indexFileReader.Read(buffer, 0, size); var block = new BlockIndex(buffer); //判断文件内容是否已经存在 if (fileDataIndex.ContainsKey(block.Hash)) { //判断文件名称是否已经存在 if (!fileNameIndex.ContainsKey(block.FileName)) { fileNameIndex.Add(block.FileName, fileDataIndex[block.Hash]); } else { fileNameIndex[block.FileName] = fileDataIndex[block.Hash]; } continue; } this.fileBlocks.Add(block); var fileIndex = this.fileBlocks.Count - 1; fileDataIndex.Add(block.Hash, fileIndex); fileNameIndex.Add(block.FileName, fileIndex); //read next one buffer = new byte[4]; indexFileReader.Read(buffer, 0, 4); size = BitConverter.ToInt32(buffer, 0); } } }