Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class FileDataSource : DataSource
- {
- private Dictionary<String, String> mimeTypes = new Dictionary<String, String>()
- {
- {".css", "text/css"},
- {".js", "text/javascript"},
- {".htm", "text/html"},
- {".html", "text/html"},
- {".htmls", "text/html"},
- {".png", "image/png"},
- {".jpg", "image/jpeg"},
- {".jpeg", "image/jpeg"},
- };
- protected override void OnRequest(DataSourceRequest request)
- {
- try
- {
- using (var stream = File.Open(request.Path, FileMode.Open, FileAccess.Read, FileShare.Read))
- {
- var size = (Int32)stream.Length;
- var data = Marshal.AllocHGlobal(size);
- var buffer = new Byte[size];
- stream.Read(buffer, 0, size);
- Marshal.Copy(buffer, 0, data, size);
- String mimeType;
- if (this.mimeTypes.TryGetValue(Path.GetExtension(request.Path), out mimeType))
- this.SendResponse(request, new DataSourceResponse() { MimeType = mimeType, Buffer = data, Size = (UInt32)size });
- else // unknown extensions are returned as "application/octet-stream" which is unknown binary.
- this.SendResponse(request, new DataSourceResponse() { MimeType = "application/octet-stream", Buffer = data, Size = (UInt32)size });
- }
- }
- catch (Exception e)
- {
- Console.WriteLine("FileDataSource:OnRequest:Exception: " + e.Message);
- this.SendResponse(request, new DataSourceResponse() { Buffer = IntPtr.Zero, Size = 0 });
- }
- }
- }
- // Usage
- // C#
- WebView.WebSession.AddDataSource("file", new FileDataSource());
- // HTML/JS
- <script type="text/javascript" src="asset://file/jquery.js"></script>
Advertisement
Add Comment
Please, Sign In to add comment