完全删除公告所有内容
开发工具与关键技术:Visual Studio
作者:胡宁淇
撰写时间:2019年4月26日
我们要完全删除一条公告需要知道它由几部分组成,一条完整的公告是分别是由整条公告内容、公告内容中的图片、轮播图片和附件组成的
整条公告内容
轮播
公告内容
附件
要删除某一条公告我们要知道它的ID,所以用int类型的参数来接收从页面传过来的ID
public ActionResult NoticeDelete(int noticeId)
{
try
{
我们根据页面传过来的ID从公告表中筛选出要删除的那条公告
PW_NoticeTable dbNotice = (from tbNotice in myModel.PW_NoticeTable
where tbNotice.NoticeID== noticeId
select tbNotice).Single();
先把整条数据从数据库删除
myModel.PW_NoticeTable.Remove(dbNotice);
匹配出公告的所有内容
string textFileName = Server.MapPath("~/Document/Notice/Text/") + dbNotice.NoticeContent;
检查公告内容是否存在
if (System.IO.File.Exists(textFileName))
{
//存在就读取原始的文本内容
string oldTextContent = System.IO.File.ReadAllText(textFileName);
//匹配出存放图片文件名称
MatchCollection oldMatchs = Regex.Matches(oldTextContent, "(?<=/Document/Notice/Image/).+?(?=\".+?/>)");
遍历循环文件夹中的图片
foreach (Match match in oldMatchs)
{
//得到存放图片的总条数
string DfilePath = Server.MapPath("~/Document/Notice/Image/") + match.Value;
try
{
//然后执行删除
System.IO.File.Delete(DfilePath);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
//删除图片后删除公告中的txt内容
System.IO.File.Delete(textFileName);
检查要删除的公告是否有附件,因为附件可能不止一条,所以用List接收
List<PW_File> listFiles = (from tbFile in myModel.PW_File
where tbFile.NoticeID ==noticeId
select tbFile).ToList();
//遍历循环查询出的附件
foreach (PW_File file in listFiles)
{
匹配出存放附件的文件夹和附件总条数
string filePath = "~/Document/Notice/Attachment/" + Regex.Match(file.Files, "(?<=fileName=).+?(?=\")").Value;
用一个变量来接收
string DfilePath = Server.MapPath(filePath);
try
{
删除存放在文件夹中的附件
System.IO.File.Delete(DfilePath);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
//删除附件表中附件数据
myModel.PW_File.RemoveRange(listFiles);
//查询要删除的公告有没有能否获取原来的轮播(可能有,可能没有)
PW_NoticeCarousel dbNoticeCarousel = (from tbNoticeCarousel in myModel.PW_NoticeCarousel
where
tbNoticeCarousel.NoticeID == noticeId
select
tbNoticeCarousel).SingleOrDefault();
如果轮播表里面有轮播,那就执行删除
if (dbNoticeCarousel != default(PW_NoticeCarousel))
{
//删除轮播图片
try
{
System.IO.File.Delete(Server.MapPath("~" + dbNoticeCarousel.NoticeCarousel));
}
catch (Exception e)
{
Console.WriteLine(e);
}
//删除轮播表中的数据
myModel.PW_NoticeCarousel.Remove(dbNoticeCarousel);
}
当myModel里的改变大于0条时,返回true,否则返回false
if (myModel.SaveChanges() > 0)
{
return Json(true, JsonRequestBehavior.AllowGet);
}
else
{
//"保存失败"
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
return Json(false, JsonRequestBehavior.AllowGet);
}