Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@darrelmiller
Created June 11, 2014 20:59
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save darrelmiller/407698a4cb4af587611b to your computer and use it in GitHub Desktop.
Save darrelmiller/407698a4cb4af587611b to your computer and use it in GitHub Desktop.
FileContent
public class FileContent : HttpContent
{
private const int DefaultBufferSize = 1024 * 64;
private readonly string _fileName;
private readonly FileInfo _fileInfo;
public FileContent(string fileName, MediaTypeHeaderValue contentType = null)
{
Headers.ContentType = contentType ?? new MediaTypeHeaderValue("application/octet-stream");
if (string.IsNullOrWhiteSpace(fileName))
{
throw new ArgumentNullException("fileName");
}
_fileInfo = new FileInfo(fileName);
if (!_fileInfo.Exists)
{
throw new FileNotFoundException(string.Empty, fileName);
}
_fileName = fileName;
}
public string FileName
{
get { return _fileName; }
}
protected override bool TryComputeLength(out long length)
{
length = _fileInfo.Length;
return true;
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
using(var fileStream = new FileStream(_fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite,
DefaultBufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan)) {
fileStream.CopyTo(stream);
};
return Task.FromResult<object>(null);
}
}
@IDisposable
Copy link

Probably would be better to do the throws on null fileName or file.Exist == false before setting the Headers.ContentType.

@IDisposable
Copy link

Also, would be much cooler to use await fileStream.CopyToAsync when on platforms that would allow it...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment