Created
June 11, 2014 20:59
-
-
Save darrelmiller/407698a4cb4af587611b to your computer and use it in GitHub Desktop.
FileContent
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
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
Probably would be better to do the throws on null fileName or file.Exist == false before setting the Headers.ContentType.