1 // Copyright 2004-2008 Castle Project - http://www.castleproject.org/
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 namespace Castle
.Core
.Resource
23 public class FileResource
: AbstractStreamResource
25 private string filePath
;
26 private String basePath
;
28 public FileResource(CustomUri resource
)
30 CreateStream
= delegate
32 return CreateStreamFromUri(resource
, DefaultBasePath
);
36 public FileResource(CustomUri resource
, String basePath
)
38 CreateStream
= delegate
40 return CreateStreamFromUri(resource
, basePath
);
44 public FileResource(String resourceName
)
46 CreateStream
= delegate
48 return CreateStreamFromPath(resourceName
, DefaultBasePath
);
52 public FileResource(String resourceName
, String basePath
)
54 CreateStream
= delegate
56 return CreateStreamFromPath(resourceName
, basePath
);
60 public override string ToString()
62 return String
.Format("FileResource: [{0}] [{1}]", filePath
, basePath
);
65 public override String FileBasePath
67 get { return basePath; }
70 public override IResource
CreateRelative(String resourceName
)
72 return new FileResource(resourceName
, basePath
);
75 private Stream
CreateStreamFromUri(CustomUri resource
, String basePath
)
77 if (resource
== null) throw new ArgumentNullException("resource");
78 if (basePath
== null) throw new ArgumentNullException("basePath");
81 throw new ArgumentException("The specified resource is not a file", "resource");
83 return CreateStreamFromPath(resource
.Path
, basePath
);
86 private Stream
CreateStreamFromPath(String filePath
, String basePath
)
89 throw new ArgumentNullException("filePath");
91 throw new ArgumentNullException("basePath");
93 if (!Path
.IsPathRooted(filePath
) || !File
.Exists(filePath
))
95 // For a relative path, we use the basePath to
96 // resolve the full path
98 filePath
= Path
.Combine(basePath
, filePath
);
101 CheckFileExists(filePath
);
103 this.filePath
= Path
.GetFileName(filePath
);
104 this.basePath
= Path
.GetDirectoryName(filePath
);
106 return File
.OpenRead(filePath
);
109 private static void CheckFileExists(String path
)
111 if (!File
.Exists(path
))
113 String message
= String
.Format("File {0} could not be found", new FileInfo(path
).FullName
);
114 throw new ResourceException(message
);