I have download files by returning as stream like below using WCF rest service.
Stream stream = null;
var directoryInformation = CommonServices.Utility.DirectoryHelper.GetTempFolderRootLocation();
string newFolderPath = directoryInformation + "\\Attachments\\" + Guid.NewGuid();
try
{
Directory.CreateDirectory(newFolderPath);
DataSet getDocumentContent = GetDocumentContent(engagementId, documentId);
var fileName = getDocumentContent.Tables[0].Rows[0]["Fullname"] as string;
var byteData= getDocumentContent.Tables[0].Rows[0]["FilestreamContent"] as byte[];
string fullPath = newFolderPath + "\\" + fileName;
using (var fileStream = new FileStream(fullPath, FileMode.Create))
{
if (byteData != null)
{
fileStream.Write(byteData,0,byteData.Length);
fileStream.Close();
}
if (WebOperationContext.Current != null)
{
WebOperationContext.Current.OutgoingResponse.ContentType = "application/octet-stream";
WebOperationContext.Current.OutgoingResponse.Headers.Add("content-disposition","inline; filename=" + fileName);
}
}
stream = File.OpenRead(fullPath);
return stream;
}
catch (Exception exception)
{
return null;
}
The above code works perfectly and can download the file in browser. But i have to delete the file after return the stream. So i have try to close and delete the file including the directory in finally block like below
finally
{
if (stream != null) stream.Close();
Directory.Delete(newFolderPath, true);
}
Full Method code
public Stream DownloadAttachment(string engagementId, string documentId)
{
Stream stream = null;
var directoryInformation = CommonServices.Utility.DirectoryHelper.GetTempFolderRootLocation();
string newFolderPath = directoryInformation + "\\Attachments\\" + Guid.NewGuid();
try
{
Directory.CreateDirectory(newFolderPath);
DataSet getDocumentContent = GetDocumentContent(engagementId, documentId);
var fileName = getDocumentContent.Tables[0].Rows[0]["Fullname"] as string;
var byteData= getDocumentContent.Tables[0].Rows[0]["FilestreamContent"] as byte[];
string fullPath = newFolderPath + "\\" + fileName;
using (var fileStream = new FileStream(fullPath, FileMode.Create))
{
if (byteData != null)
{
fileStream.Write(byteData,0,byteData.Length);
fileStream.Close();
}
if (WebOperationContext.Current != null)
{
WebOperationContext.Current.OutgoingResponse.ContentType = "application/octet-stream";
WebOperationContext.Current.OutgoingResponse.Headers.Add("content-disposition","inline; filename=" + fileName);
}
}
stream = File.OpenRead(fullPath);
return stream;
}
catch (Exception exception)
{
return null;
}
finally
{
if (stream != null) stream.Close();
Directory.Delete(newFolderPath, true);
}
}
After adding this code file is not downloaded in client.Is there any way to delete the file?Please help me to resolve this