如何从项目中的文件夹中删除文件

问题描述:

实际上我正在从本地电脑上传一个文件...在上传时我将路径保存到一个表作为记录同时我将文件保存到一个文件夹中它已成功完成但是......当我想要的时候从同一时间删除该表中的一条记录我想要删除保存在文件夹中的那条记录的文件...是否可能。

Actually i am uploading one file from local pc...while uploading i am saving the path into one table as a record at the same time i am saving the file into one folder it is done successfully but..when i want to delete one record from that table at the same time i want to delete file of that record which is saved in folder also...is it possible.

是。

这是两个操作,但它只是按顺序发出SQL DELETE和File.Delete的情况。

我可能会做什么是启动一个事务,然后输入一个try..catch块。发出SQL DELETE,然后发出File.Delete以删除文件,然后提交事务。在catch块中,回滚以便如果删除它时DB仍然引用该文件(除非异常是找不到文件,在这种情况下仍然提交它以使它们恢复同步)
Yes.
It''s two operations, but it''s just a case of issuing a SQL DELETE and a File.Delete in sequence.
What I would probably do is start a transaction, then enter a try..catch block. Issue the SQL DELETE, then the File.Delete to remove the file, then commit the transaction. In the catch block, rollback so that the DB still refers to the file if there is a problem with deleting it (unless the exception is "file not found" in which case commit it anyway to get them back into sync)


string rootFolderPath = @"C:\\SomeFolder\\AnotherFolder\\FolderCOntainingThingsToDelete";
string filesToDelete = @"*DeleteMe*.doc";   // Only delete DOC files containing "DeleteMe" in their filenames
string[] fileList = System.IO.Directory.GetFiles(rootFolderPath, filesToDelete);
foreach(string file in fileList)
{
    System.Diagnostics.Debug.WriteLine(file + "will be deleted");
//  System.IO.File.Delete(file);
}





以上方法将删除文件夹中的所有文件





above method will delete All File in the Folder

System.IO.File.Delete(filePath as String);





以上方法将删除单个文件



above method will delete Single File


FileInfo TheFile = new FileInfo(Server.MapPath("") + "//Folder_Name//" + File_Name);
                if (TheFile.Exists)
                {
                    File.Delete(Server.MapPath("") + "//Folder_Name//" + File_Name););
                }