Statistics
| Branch: | Revision:

root / trunk / Pithos.Core / Agents / FileInfoExtensions.cs @ 4f6d51d4

History | View | Annotate | Download (1.7 kB)

1
using System;
2
using System.Collections.Generic;
3
using System.Diagnostics.Contracts;
4
using System.Linq;
5
using System.Text;
6
using System.IO;
7
using System.Text.RegularExpressions;
8
using System.Threading.Tasks;
9
using Pithos.Network;
10

    
11
namespace Pithos.Core.Agents
12
{
13
    static class FileInfoExtensions
14
    {
15
        
16

    
17
        public static int Read(this FileInfo fileInfo,byte[] buffer,int offset,int count)
18
        {            
19
            //Open the stream only long enough to read a block
20
            using (var stream = fileInfo.OpenRead())
21
            {
22
                stream.Seek(offset, SeekOrigin.Begin);
23
                return  stream.Read(buffer, 0, count);                
24
            }
25
        }
26

    
27
       public static string CalculateHash(this FileSystemInfo info,int blockSize,string algorithm)
28
        {
29
            if (info==null)
30
                throw new ArgumentNullException("info");
31
            if (String.IsNullOrWhiteSpace(info.FullName))
32
                throw new ArgumentException("info");
33
            if (blockSize<=0)
34
                throw new ArgumentOutOfRangeException("blockSize",blockSize,"blockSize must be greater than 0");
35
            if (String.IsNullOrWhiteSpace(algorithm))
36
                throw new ArgumentNullException("algorithm");
37
            Contract.EndContractBlock();
38

    
39
           //The hash for directories is an empty string
40
           if (info is DirectoryInfo)
41
                return String.Empty;
42
           
43
           var fileInfo = (FileInfo)info;
44
           if (fileInfo.Length <= blockSize)
45
                return Signature.CalculateMD5(info.FullName);
46
            else
47
                return Signature.CalculateTreeHash(info.FullName, blockSize, algorithm).TopHash.ToHashString();
48

    
49
        }
50

    
51
       
52

    
53
    }
54
}