Frage

I use Interop to SaveAs(D:/Temp) a template excel sheet after the changes are made. Then I use FileStream to send the user a Pop-up to save this file. But that file in D:\Temp still exists. Is there a way to delete this file on Pop-up response?

//Save the Excel File
SaveExcelFile(exportPath, sourceFile, excelWorkBook,
                excelApllication, excelWorkSheet);

#region Pop Up and File Open
if (System.IO.File.Exists(sourceFile))
{
    FileStream fsSource = 
        new FileStream(sourceFile, FileMode.Open, FileAccess.Read);

    return File(fsSource, "application/vnd.ms-excel", "FileName" + .xls");
}
else
{
    return View();
}
#endregion
War es hilfreich?

Lösung 3

Instead of creating a temp file, loading it to stream, and then trying to delete it, I suggest that you create the file directly in memory stream (i.e. System.IO.MemoryStream) in the first place, so you don't have to load it and delete it.

If you cannot create it directly in memory stream, the main issue is that you cannot delete the temp file while you're using it in the FileStream. In this case, you copy the FileStream to a MemoryStream, close and dispose the FileStream, delete the temp file, and then return the MemoryStream to the user.

You can use the function bellow to copy streams correctly.

// Author: Racil Hilan.
/// <summary>Copies data from a source stream to a target stream.</summary>
private static void CopyStream(Stream SourceStream, Stream TargetStream) {
  const int BUFFER_SIZE = 4096;
  byte[] buffer = new byte[BUFFER_SIZE];
  //Reset the source stream in order to process all data.
  if (SourceStream.CanSeek)
    SourceStream.Position = 0;
  //Copy data from the source stream to the target stream.
  int BytesRead = 0;
  while ((BytesRead = SourceStream.Read(buffer, 0, BUFFER_SIZE)) > 0)
    TargetStream.Write(buffer, 0, BytesRead);
  //Reset the source stream and the target stream to make them ready for any other operation.
  if (SourceStream.CanSeek)
    SourceStream.Position = 0;
  if (TargetStream.CanSeek)
    TargetStream.Position = 0;
}

Andere Tipps

To delete one file

string filePath)= @"C:\MyDir\filename.txt";
public bool RemoveFile(string filePath)
{
try
{
if (File.Exists(filePath))
{
File.Delete(filePath);
return true;
}
else
return true;
}
catch (Exception ex)
{
return false;
}
}

Delete all files

string[] filePaths = Directory.GetFiles(@"c:\MyDir\");
foreach (string filePath in filePaths)
  File.Delete(filePath);

To delete all files using one code line

Array.ForEach(Directory.GetFiles(@"c:\MyDir\"),
              delegate(string path) { File.Delete(path); });

You can use File.Delete method.

if (File.Exists("File_Path"))
{
 File.Delete("File_Path");
}

Updated

For downloading binary files,

using (FileStream fs = File.OpenRead(path))
{
    int length = (int)fs.Length;
    byte[] buffer;

    using (BinaryReader br = new BinaryReader(fs))
    {
        buffer = br.ReadBytes(length);
    }

    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", String.Format("attachment;filename={0}", Path.GetFileName(path)));
    Response.ContentType = "application/" + Path.GetExtension(path).Substring(1);
    Response.BinaryWrite(buffer);
    Response.Flush();
    Response.End();
}

Found this code from here

You can use File.Delete() for this. Just make sure you've closed the stream before you try to delete the file, and preferably, that you have been able to send whatever you need to.

I'm guessing you don't want to delete the file if the main operation fails.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top