FileContent.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System.IO;
  2. using System.Net;
  3. using System.Net.Http;
  4. using System.Net.Http.Headers;
  5. using System.Threading.Tasks;
  6. namespace EasyDevCore.Remote.HttpAccess
  7. {
  8. /// <summary>
  9. /// Represents HTTP content based on a local file. Typically used with PostMultipartAsync for uploading files.
  10. /// </summary>
  11. public class FileContent : HttpContent
  12. {
  13. /// <summary>
  14. /// The local file path.
  15. /// </summary>
  16. public string Path { get; }
  17. private readonly int _BufferSize;
  18. /// <summary>
  19. /// Initializes a new instance of the <see cref="FileContent" /> class.
  20. /// </summary>
  21. /// <param name="path">The local file path.</param>
  22. /// <param name="bufferSize">The buffer size of the stream upload in bytes. Defaults to 4096.</param>
  23. public FileContent(string path, int bufferSize = 4096)
  24. {
  25. Path = path;
  26. _BufferSize = bufferSize;
  27. }
  28. /// <summary>
  29. /// Serializes to stream asynchronous.
  30. /// </summary>
  31. /// <param name="stream">The stream.</param>
  32. /// <param name="context">The context.</param>
  33. /// <returns></returns>
  34. protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
  35. {
  36. using(var fs = new FileStream(Path, FileMode.Open, FileAccess.Read, FileShare.Read, _BufferSize, useAsync: true))
  37. {
  38. await fs.CopyToAsync(stream, _BufferSize).ConfigureAwait(false);
  39. }
  40. }
  41. /// <summary>
  42. /// Tries the length of the compute.
  43. /// </summary>
  44. /// <param name="length">The length.</param>
  45. /// <returns></returns>
  46. protected override bool TryComputeLength(out long length)
  47. {
  48. length = -1;
  49. return false;
  50. }
  51. }
  52. }