定義 Web 檔案系統抽象基類,包含共用邏輯 (GZip 傳輸、資料夾建立、快取標頭) 與工廠方法根據路由配置建立具體實現。
using System;
using System.IO;
using System.Web;
namespace Step1.WebFileSystem {
public class FileSystem {
protected string path, physicsPath;
protected Handler handle;
protected HttpContext httpContext = null;
protected Stream stream = null;
public FileSystem(string path, Handler handle) {
httpContext = HttpContext.Current;
this.path = path;
this.physicsPath = httpContext.Server.MapPath(path);
this.handle = handle;
}
public virtual bool Exists() { return false; }
public virtual DateTime GetLastWriteTime() { return DateTime.Now; }
public virtual Stream GetWriter() {
stream = httpContext.Response.OutputStream;
if (this.handle.UseGzip) return new GZipOutputStream(stream);
return stream;
}
public virtual Stream GetReader() { return null; }
public virtual void TransmitFile() { return; }
public virtual void Close() {
if (stream != null) { stream.Close(); stream = null; }
}
public virtual void Dispose() { Close(); }
public void TransmitStream(bool unZip) {
Stream reader = unZip ? new GZipInputStream(this.GetReader()) : this.GetReader();
byte[] buffer = new byte[1024];
int p;
while ((p = reader.Read(buffer, 0, 1024)) > 0) {
httpContext.Response.OutputStream.Write(buffer, 0, p);
httpContext.Response.Flush();
}
this.Close();
}
public void ResponseFile() {
HttpRequest request = httpContext.Request;
string acceptEncoding = request.Headers["Accept-Encoding"];
if (this.handle.UseGzip && acceptEncoding != null && acceptEncoding.IndexOf("gzip") >= 0) {
httpContext.Response.AddHeader("Content-Encoding", "gzip");
this.TransmitFile();
} else {
if (this.handle.UseGzip) this.TransmitStream(true);
else this.TransmitFile();
}
}
protected void CreateFolder(string path, bool createCurrent) {
string folder = Path.GetDirectoryName(path);
if (!Directory.Exists(folder)) CreateFolder(folder, true);
if (createCurrent) Directory.CreateDirectory(path);
}
public static FileSystem Create(string path) {
Configuration config = Configuration.Instance();
if (config != null) {
for (int i = 0; i < config.handlers.Length; i++) {
if (config.handlers[i].UrlRegex.IsMatch(path)) {
switch (config.handlers[i].HandlerType) {
case "FFS": return new FileSystemFFS(path, config.handlers[i]);
case "OS": return new FileSystemOS(path, config.handlers[i]);
default: return new FileSystem(path, config.handlers[i]);
}
}
}
}
return new FileSystem(path, new Handler());
}
}
}
架構亮點:
ResponseFile 定義傳輸流程,子類實現具體存取Create 根據正則路由動態建立 FFS/OS/基類實例Close/Dispose 模式確保串流釋放