我有一个 WCF 服务,它返回一个 Stream,如下所示:
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;
}
我曾经尝试返回 null,但如果找不到文件,我开始遇到这个问题:WCF - MessageBodyMember - 流 -“值不能为空” https://stackoverflow.com/questions/7319019/wcf-messagebodymember-stream-value-cannot-be-null
通过返回 Stream.Null,我已经摆脱了该错误,但现在我遇到了另一个问题 - 我的客户如何知道我是否发回了 Stream.Null?我不能/不应该检查长度,因为这些文件可能很大,但即使不是,我也会遇到这个问题:在 WCF 客户端中查找 Stream 对象的长度? https://stackoverflow.com/questions/11848570/find-length-of-stream-object-in-wcf-client
这是我的(非常简化的)客户端代码,仅供后代使用,但对我来说,仅下载 Stream.Null 的问题是我最终会得到一个空文件,没有人喜欢这样。
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);
}
看来我只是以某种方式设计了这个方法错误,但我想不出更好的方法来做到这一点,而不涉及抛出未捕获的异常。有什么建议么?