gpt4 book ai didi

c# - ASP.NET 计划删除临时文件

转载 作者:太空狗 更新时间:2023-10-30 00:46:36 24 4
gpt4 key购买 nike

问题:我有一个创建临时 PDF 文件(供用户下载)的 ASP.NET 应用程序。现在,许多用户在几天内可以创建许多 PDF,这会占用大量磁盘空间。

安排删除超过 1 天/8 小时的文件的最佳方法是什么?最好在 asp.net 应用程序本身中...

最佳答案

对于您需要创建的每个临时文件,记下 session 中的文件名:

// create temporary file:
string fileName = System.IO.Path.GetTempFileName();
Session[string.Concat("temporaryFile", Guid.NewGuid().ToString("d"))] = fileName;
// TODO: write to file

接下来,将以下清理代码添加到 global.asax:

<%@ Application Language="C#" %>
<script RunAt="server">
void Session_End(object sender, EventArgs e) {
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.

// remove files that has been uploaded, but not actively 'saved' or 'canceled' by the user
foreach (string key in Session.Keys) {
if (key.StartsWith("temporaryFile", StringComparison.OrdinalIgnoreCase)) {
try {
string fileName = (string)Session[key];
Session[key] = string.Empty;
if ((fileName.Length > 0) && (System.IO.File.Exists(fileName))) {
System.IO.File.Delete(fileName);
}
} catch (Exception) { }
}
}

}
</script>

更新:我现在准确地使用了一种新的(改进的)方法,而不是上述方法。新的涉及 HttpRuntime.Cache 并检查文件是否超过 8 小时。如果有人感兴趣,我会在这里发布。这是我的新 global.asax.cs:

using System;
using System.Web;
using System.Text;
using System.IO;
using System.Xml;
using System.Web.Caching;

public partial class global : System.Web.HttpApplication {
protected void Application_Start() {
RemoveTemporaryFiles();
RemoveTemporaryFilesSchedule();
}

public void RemoveTemporaryFiles() {
string pathTemp = "d:\\uploads\\";
if ((pathTemp.Length > 0) && (Directory.Exists(pathTemp))) {
foreach (string file in Directory.GetFiles(pathTemp)) {
try {
FileInfo fi = new FileInfo(file);
if (fi.CreationTime < DateTime.Now.AddHours(-8)) {
File.Delete(file);
}
} catch (Exception) { }
}
}
}

public void RemoveTemporaryFilesSchedule() {
HttpRuntime.Cache.Insert("RemoveTemporaryFiles", string.Empty, null, DateTime.Now.AddHours(1), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, delegate(string id, object o, CacheItemRemovedReason cirr) {
if (id.Equals("RemoveTemporaryFiles", StringComparison.OrdinalIgnoreCase)) {
RemoveTemporaryFiles();
RemoveTemporaryFilesSchedule();
}
});
}
}

关于c# - ASP.NET 计划删除临时文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2833020/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com