c# - Delete a Temp File after FileStream Pop-Up response -
i use interop saveas(d:/temp) template excel sheet after changes made. use filestream
send user pop-up save file. file in d:\temp still exists. there way delete file on pop-up response?
//save excel file saveexcelfile(exportpath, sourcefile, excelworkbook, excelapllication, excelworksheet); #region pop , 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
instead of creating temp file, loading stream, , trying delete it, suggest create file directly in memory stream (i.e. system.io.memorystream
) in first place, don't have load , delete it.
if cannot create directly in memory stream, main issue cannot delete temp file while you're using in filestream. in case, copy filestream memorystream, close , dispose filestream, delete temp file, , return memorystream user.
you can use function bellow copy streams correctly.
// author: racil hilan. /// <summary>copies data source stream target stream.</summary> private static void copystream(stream sourcestream, stream targetstream) { const int buffer_size = 4096; byte[] buffer = new byte[buffer_size]; //reset source stream in order process data. if (sourcestream.canseek) sourcestream.position = 0; //copy data source stream target stream. int bytesread = 0; while ((bytesread = sourcestream.read(buffer, 0, buffer_size)) > 0) targetstream.write(buffer, 0, bytesread); //reset source stream , target stream make them ready other operation. if (sourcestream.canseek) sourcestream.position = 0; if (targetstream.canseek) targetstream.position = 0; }
Comments
Post a Comment