【问题标题】:Delete a Temp File after FileStream Pop-Up responseFileStream Pop-Up 响应后删除临时文件
【发布时间】:2014-03-06 12:03:56
【问题描述】:

在进行更改后,我使用 Interop 将模板 Excel 表另存为(D:/Temp)。 然后我使用FileStream 向用户发送一个弹出窗口来保存这个文件。但是 D:\Temp 中的那个文件仍然存在。 有没有办法在弹出响应中删除此文件?

//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

【问题讨论】:

    标签: c# asp.net-mvc filestream


    【解决方案1】:

    删除一个文件

    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;
    }
    }
    

    删除所有文件

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

    使用一行代码删除所有文件

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

    【讨论】:

      【解决方案2】:

      你可以使用File.Delete方法。

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

      更新

      用于下载binary文件,

      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();
      }
      

      here找到此代码

      【讨论】:

      • 我不认为文件流会允许文件在使用时被删除。
      • 确认:如果 File.Delete(); 放在 return 语句之前,应用程序会出错。
      • 返回后接下来会发生什么?我的意思是代码流
      • Response.WriteFile(filepath); 是否在您提供用户下载文件的选项中?
      • return 语句给了我一个弹出窗口来保存文件。此功能的流程到此结束。
      【解决方案3】:

      我建议您首先直接在内存流中创建文件(即System.IO.MemoryStream),而不是创建一个临时文件,将其加载到流中,然后尝试删除它,这样您就没有加载它并删除它。

      如果您不能直接在内存流中创建它,主要问题是您在 FileStream 中使用临时文件时无法删除它。在这种情况下,您将 FileStream 复制到 MemoryStream,关闭并处置 FileStream,删除临时文件,然后将 MemoryStream 返回给用户。

      您可以使用下面的功能正确复制流。

      // 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;
      }
      

      【讨论】:

      • 我有点需要 Interop 的 SaveAs 来做我需要做的事情。我可以将 SaveAs 保存到 MemoryStream 中吗?
      • 我不知道,您必须检查它是否具有采用流而不是文件的重载。或者也许它有另一种方法。如果是这样,那么是的,您可以保存到 MemoryStream 中。如果没有,我刚刚编辑了我的答案。您可以将 FileStream 复制到 MemoryStream。
      • 编辑:效果很好!但是保存的文件没有正确的数据。 :(
      • 更新:我阅读了你的方法并即兴创作并做了这样的事情:fsSource.CopyTo(MsSource); if (MsSource.CanSeek) { MsSource.Position = 0; } 它有效!
      • 是的,正如我所提到的,在处理流时很容易犯小错误。将源流返回到开始位置对于复制后的代码很重要。至于您关于缓冲区类型的问题,您可以使用任何值。默认值 4096 表示 4 KB 块,在大多数情况下可能是内存使用和性能之间的良好平衡,但在某些情况下,另一个值可能更好。请参阅文档msdn.microsoft.com/en-us/library/dd783870(v=vs.110).aspx
      【解决方案4】:

      您可以为此使用File.Delete()。在您尝试删除文件之前确保您已关闭流,最好确保您能够发送您需要的任何内容。

      如果主操作失败,我猜你不想删除文件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-07
        • 1970-01-01
        • 2010-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多