Statistics
| Branch: | Revision:

root / trunk / Pithos.Interfaces / FileInfoExtensions.cs @ 5e31048f

History | View | Annotate | Download (1.9 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

    
10

    
11
namespace Pithos.Interfaces
12
{
13
    public static class FileInfoExtensions
14
    {
15
        public static  string AsRelativeTo(this FileInfo fileInfo,string path )
16
        {
17
            if (String.IsNullOrWhiteSpace(path))
18
                throw new ArgumentNullException("path");            
19
            Contract.EndContractBlock();
20
            Contract.Assume(Enum.IsDefined(typeof(StringComparison),StringComparison.InvariantCultureIgnoreCase));
21

    
22
            if (!path.EndsWith("\\"))
23
                path=path.ToLower() + "\\";
24
            int pathLength = path.Length;            
25
            
26
            var filePath = fileInfo.FullName;
27
            
28
            if (!filePath.StartsWith(path,StringComparison.InvariantCultureIgnoreCase))
29
                throw new ArgumentException(String.Format("The path {0} doesn't contain the file {1}",path,filePath));
30
            
31
            var relativePath = filePath.Substring(pathLength, filePath.Length - pathLength);
32

    
33
            return relativePath;
34
        }
35

    
36
        public static string AsRelativeUrlTo(this FileInfo fileInfo,string path )
37
        {
38
            if (String.IsNullOrWhiteSpace(path))
39
                throw new ArgumentNullException("path");
40
            Contract.EndContractBlock();
41

    
42
            var relativePath = fileInfo.AsRelativeTo(path);
43
            var replacedSlashes = relativePath.Replace("\\","/");
44
            var escaped = Uri.EscapeUriString(replacedSlashes);
45
            return escaped;
46
        }
47

    
48
        public static string RelativeUriToFilePath(this Uri uri)
49
        {
50
            var unescaped = Uri.UnescapeDataString(uri.ToString());
51
            var path = unescaped.Replace("/", "\\");
52
            return path;
53
        }
54

    
55

    
56

    
57
    }
58
}