Statistics
| Branch: | Revision:

root / trunk / Pithos.Interfaces / FileInfoExtensions.cs @ c945b450

History | View | Annotate | Download (8.6 kB)

1
#region
2
/* -----------------------------------------------------------------------
3
 * <copyright file="FileInfoExtensions.cs" company="GRNet">
4
 * 
5
 * Copyright 2011-2012 GRNET S.A. All rights reserved.
6
 *
7
 * Redistribution and use in source and binary forms, with or
8
 * without modification, are permitted provided that the following
9
 * conditions are met:
10
 *
11
 *   1. Redistributions of source code must retain the above
12
 *      copyright notice, this list of conditions and the following
13
 *      disclaimer.
14
 *
15
 *   2. Redistributions in binary form must reproduce the above
16
 *      copyright notice, this list of conditions and the following
17
 *      disclaimer in the documentation and/or other materials
18
 *      provided with the distribution.
19
 *
20
 *
21
 * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
22
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
25
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
28
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32
 * POSSIBILITY OF SUCH DAMAGE.
33
 *
34
 * The views and conclusions contained in the software and
35
 * documentation are those of the authors and should not be
36
 * interpreted as representing official policies, either expressed
37
 * or implied, of GRNET S.A.
38
 * </copyright>
39
 * -----------------------------------------------------------------------
40
 */
41
#endregion
42
using System;
43
using System.Collections.Generic;
44
using System.Diagnostics.Contracts;
45
using System.Linq;
46
using System.Text;
47
using System.IO;
48
using System.Text.RegularExpressions;
49
using System.Threading.Tasks;
50

    
51

    
52
namespace Pithos.Interfaces
53
{
54
    public static class FileInfoExtensions
55
    {
56
        public static  string AsRelativeTo(this FileSystemInfo fileInfo,string path )
57
        {
58
            if (String.IsNullOrWhiteSpace(path))
59
                throw new ArgumentNullException("path");            
60
            Contract.EndContractBlock();
61
            Contract.Assume(Enum.IsDefined(typeof(StringComparison),StringComparison.InvariantCultureIgnoreCase));
62

    
63
            if (!path.EndsWith("\\"))
64
                path=path.ToLower() + "\\";
65
            int pathLength = path.Length;            
66
            
67
            var filePath = fileInfo.GetProperCapitalization();
68
            
69
            if (!filePath.StartsWith(path,StringComparison.InvariantCultureIgnoreCase))
70
                throw new ArgumentException(String.Format("The path {0} doesn't contain the file {1}",path,filePath));
71
            
72
            var relativePath = filePath.Substring(pathLength, filePath.Length - pathLength);
73

    
74
            return relativePath;
75
        }
76

    
77
        public static string AsRelativeUrlTo(this FileSystemInfo fileInfo,string path )
78
        {
79
            if (String.IsNullOrWhiteSpace(path))
80
                throw new ArgumentNullException("path");
81
            Contract.EndContractBlock();
82

    
83
            var relativePath = fileInfo.AsRelativeTo(path);
84
            var replacedSlashes = relativePath.Replace("\\","/");
85
            var escaped = Uri.EscapeUriString(replacedSlashes);
86
            return escaped;
87
        }
88

    
89
        public static string RelativeUriToFilePath(this Uri uri)
90
        {
91
            var unescaped = Uri.UnescapeDataString(uri.ToString());
92
            var path = unescaped.Replace("/", "\\");
93
            return path;
94
        }
95

    
96

    
97
        public static string GetProperDirectoryCapitalization(string fileName)
98
        {
99
            Contract.Ensures(!String.IsNullOrWhiteSpace(Contract.Result<string>()));
100
            Contract.EndContractBlock();
101
            
102
            if (String.IsNullOrWhiteSpace(fileName))
103
                return String.Empty;
104

    
105
            var dirInfo = new DirectoryInfo(fileName);
106
            return dirInfo.GetProperCapitalization();
107
        }
108

    
109

    
110
        public static string GetProperCapitalization(this DirectoryInfo dirInfo)
111
        {
112
            if (dirInfo == null)
113
                throw new ArgumentNullException("dirInfo");
114
            Contract.EndContractBlock();
115
            Contract.Assume(!String.IsNullOrWhiteSpace(dirInfo.FullName));
116

    
117
            var parentDirInfo = dirInfo.Parent;
118
            if (null == parentDirInfo)
119
                return dirInfo.Name;
120

    
121
            try
122
            {
123

    
124
                dirInfo.Refresh();
125

    
126
                if (dirInfo.Exists)
127
                    return Path.Combine(GetProperDirectoryCapitalization(parentDirInfo.FullName),
128
                                        parentDirInfo.GetDirectories(dirInfo.Name)[0].Name);
129
                else
130
                {
131
                    return dirInfo.FullName;
132
                }
133
            }
134
            catch (DirectoryNotFoundException)
135
            {
136
                //An exception can occur if a directory is deleted right after the Exists call
137
                return dirInfo.FullName;
138
            }
139
        }
140

    
141

    
142
        public static string GetProperFilePathCapitalization(string fileName)
143
        {
144
            Contract.Ensures(!String.IsNullOrWhiteSpace(Contract.Result<string>()));
145
            Contract.EndContractBlock();
146
            if (String.IsNullOrWhiteSpace(fileName))
147
                return String.Empty;
148

    
149

    
150
            var fileInfo = new FileInfo(fileName);
151
            return fileInfo.GetProperCapitalization();
152
        }
153

    
154
        public static string GetProperCapitalization(this FileInfo fileInfo)
155
        {
156
            if (fileInfo == null)
157
                throw new ArgumentNullException("fileInfo");
158
            Contract.EndContractBlock();
159

    
160

    
161
            var dirInfo = fileInfo.Directory;
162

    
163
            //Directory will not be null for an absolute path
164
            Contract.Assume(dirInfo != null);
165

    
166
            try
167
            {
168
                //Exists returns a cached value that can be true even if a file was deleted since the
169
                //FileInfo object was created.
170
                fileInfo.Refresh();
171
                if (fileInfo.Exists)
172
                    return Path.Combine(GetProperDirectoryCapitalization(dirInfo.FullName),
173
                                        dirInfo.GetFiles(fileInfo.Name)[0].Name);
174
                else
175
                {
176
                    return fileInfo.FullName;
177
                }
178
            }
179
            catch (FileNotFoundException)
180
            {
181
                //An exception can occur if a file is deleted right after the Exists call
182
                return fileInfo.FullName;
183

    
184
            }
185
        }
186

    
187
        public static string GetProperCapitalization(this FileSystemInfo info)
188
        {
189
            if (info is FileInfo)
190
                return (info as FileInfo).GetProperCapitalization();
191
            if (info is DirectoryInfo)
192
                return (info as DirectoryInfo).GetProperCapitalization();
193
            throw new NotSupportedException("Unexpected parameter type");
194
        }
195

    
196
        public static DirectoryInfo WithProperCapitalization(this DirectoryInfo dirInfo)
197
        {
198
            if (dirInfo==null)
199
                throw new ArgumentNullException("dirInfo");
200
            Contract.EndContractBlock();
201

    
202
            var path = dirInfo.GetProperCapitalization();
203
            return new DirectoryInfo(path);
204
        }
205

    
206
        public static FileInfo WithProperCapitalization(this FileInfo fileInfo)
207
        {
208
            if (fileInfo==null)
209
                throw new ArgumentNullException("fileInfo");
210
            Contract.EndContractBlock();
211

    
212
            var path = fileInfo.GetProperCapitalization();
213
            return new FileInfo(path);
214
        }
215

    
216
        public static FileSystemInfo WithProperCapitalization(this FileSystemInfo info)
217
        {
218
            if (info==null)
219
                throw new ArgumentNullException("info");
220
            Contract.EndContractBlock();
221

    
222
            if (info is FileInfo)
223
                return (info as FileInfo).WithProperCapitalization();
224
            if (info is DirectoryInfo)
225
                return (info as DirectoryInfo).WithProperCapitalization();
226

    
227
            throw new NotSupportedException("Unexpected parameter type");
228
        }
229

    
230
        public static FileSystemInfo FromPath(string filePath)
231
        {
232
            if (String.IsNullOrWhiteSpace(filePath))
233
                throw new ArgumentNullException("filePath");
234
            Contract.EndContractBlock();
235

    
236
            return Directory.Exists(filePath) ? 
237
                (FileSystemInfo) new DirectoryInfo(filePath) 
238
                : new FileInfo(filePath);
239
        }
240
    }
241
}