I have a WCF service which returns a Stream much like the following:
public Stream StreamFile(string filepath)
{
try
{
// Grab the file from wherever it is
// Throw an exception if it doesn't exist
return fileStream;
}
catch (Exception ex)
{
// Log the exception nicely in a place of my user's choosing
}
return Stream.Null;
}
I used to attempt to return null, but I began running into this issue if the file could not be found: WCF - MessageBodyMember - Stream - "Value cannot be null"
By returning Stream.Null, I've gotten rid of that error, but now I have another problem - how does my client know if I sent back Stream.Null? I can't/shouldn't check the length, because these files can be quite big, but even if they weren't, I would be faced with this problem: Find Length of Stream object in WCF Client?
Here's my (much-simplified) client code, just for posterity, but the issue for me with just downloading the Stream.Null is that I end up with an empty file, and nobody likes that.
public FileInfo RetrieveFile(string fileToStream, string directory)
{
Stream reportStream;
string filePath = Path.Combine(directory, "file.txt");
using (Stream incomingStream = server.StreamFile(fileToStream))
{
if (incomingStream == null) throw new FileExistsException(); // Which totally doesn't work
using (FileStream outgoingStream = File.Open(filePath, FileMode.Create, FileAccess.Write))
{
incomingStream.CopyTo(outgoingStream);
}
}
return new FileInfo(filePath);
}
It seems like I'm just designing this method wrong somehow, but I can't think of a better way to do it that doesn't involve throwing an uncaught exception. Any suggestions?