Guest User

Untitled

a guest
May 17th, 2014
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.97 KB | None | 0 0
  1.     class FileDataSource : DataSource
  2.     {
  3.         private Dictionary<String, String> mimeTypes = new Dictionary<String, String>()
  4.         {
  5.             {".css", "text/css"},
  6.  
  7.             {".js", "text/javascript"},
  8.  
  9.             {".htm", "text/html"},
  10.             {".html", "text/html"},
  11.             {".htmls", "text/html"},
  12.            
  13.             {".png", "image/png"},
  14.             {".jpg", "image/jpeg"},
  15.             {".jpeg", "image/jpeg"},
  16.         };
  17.  
  18.         protected override void OnRequest(DataSourceRequest request)
  19.         {
  20.             try
  21.             {
  22.                 using (var stream = File.Open(request.Path, FileMode.Open, FileAccess.Read, FileShare.Read))
  23.                 {
  24.                     var size = (Int32)stream.Length;
  25.                     var data = Marshal.AllocHGlobal(size);
  26.                     var buffer = new Byte[size];
  27.                     stream.Read(buffer, 0, size);
  28.                     Marshal.Copy(buffer, 0, data, size);
  29.  
  30.                     String mimeType;
  31.                     if (this.mimeTypes.TryGetValue(Path.GetExtension(request.Path), out mimeType))
  32.                         this.SendResponse(request, new DataSourceResponse() { MimeType = mimeType, Buffer = data, Size = (UInt32)size });
  33.                     else // unknown extensions are returned as "application/octet-stream" which is unknown binary.
  34.                         this.SendResponse(request, new DataSourceResponse() { MimeType = "application/octet-stream", Buffer = data, Size = (UInt32)size });
  35.                 }
  36.             }
  37.             catch (Exception e)
  38.             {
  39.                 Console.WriteLine("FileDataSource:OnRequest:Exception: " + e.Message);
  40.                 this.SendResponse(request, new DataSourceResponse() { Buffer = IntPtr.Zero, Size = 0 });
  41.             }
  42.         }
  43.     }
  44.  
  45. // Usage
  46. // C#
  47. WebView.WebSession.AddDataSource("file", new FileDataSource());
  48. // HTML/JS
  49. <script type="text/javascript" src="asset://file/jquery.js"></script>
Advertisement
Add Comment
Please, Sign In to add comment