Advertisement
Schnuk

Untitled

Oct 22nd, 2021
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Net;
  5. using System.Text;
  6. using System.Text.RegularExpressions;
  7.  
  8. namespace selfHostedHttp
  9. {
  10. class Program
  11. {
  12. static void Main(string[] args)
  13. {
  14. var listener = new HttpListener();
  15. listener.Prefixes.Add("http://localhost:8080/");
  16. listener.Start();
  17. Console.WriteLine("Сервер начал прослушивание порта 8080");
  18. var path = GetPathHTMLFiles();
  19. try
  20. {
  21. while (true)
  22. {
  23. var context = listener.GetContext();
  24. var request = context.Request;
  25. var response = context.Response;
  26. var neededFile = request.Url.AbsolutePath;
  27. string sendedFile = null;
  28. if (neededFile == "/")
  29. neededFile = "/firstPage.html";
  30. else
  31. {
  32. if (File.Exists(path + neededFile))
  33. sendedFile = neededFile;
  34. else
  35. sendedFile = "/errorPage.html";
  36. }
  37.  
  38. var bytes = File.ReadAllBytes(path + sendedFile);
  39. response.ContentLength64 = bytes.Length;
  40.  
  41. var sw = response.OutputStream;
  42. sw.Write(bytes, 0, bytes.Length);
  43. sw.Close();
  44. }
  45. }
  46. catch
  47. {
  48. listener.Stop();
  49. Console.WriteLine("Сервер закончил прослушивание порта 8080");
  50. }
  51. }
  52.  
  53. private static string GetPathHTMLFiles()
  54. {
  55. var path = GetParentSeveralTimes(4);
  56. path += "\\www_root";
  57. return path;
  58. }
  59.  
  60. private static string GetParentSeveralTimes(int count)
  61. {
  62. var path = Environment.CurrentDirectory;
  63. for (var i = 0; i < count; i++)
  64. path = Directory.GetParent(path).ToString();
  65. return path;
  66. }
  67. }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement