Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@IDisposable IDisposable commented Jul 15, 2014

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

@IDisposable

This comment has been minimized.

Copy link

@IDisposable IDisposable commented Jul 15, 2014

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