如何使用asp.net从文件夹中删除特定文件
本文关键字:删除 文件 文件夹 何使用 asp net | 更新日期: 2023-09-27 17:51:07
这里的交易我得到了一个datagridviewer,称为gridview1和fileupload1当我上传一个文件时,它更新gridview1和数据库中的表与文件名和路径,并将上述文件存储在文件夹"Mag"…但现在我想做的是相反的,我得到了如何使用gridview来删除表项,但从文件夹"Mag"删除文件是不工作已经使用以下代码在c#或代码背后
protected void GridView1_Del(object sender, EventArgs e)
{
string DeleteThis = GridView1.SelectedRow.Cells[0].Text;
string[] Files = Directory.GetFiles(@"i:/Website/WebSite3/Mag/");
foreach (string file in Files)
{
if (file.ToUpper().Contains(DeleteThis.ToUpper()))
{
File.Delete(file);
}
}
}
显示错误
"对象引用未设置为对象的实例。"
请告诉我我做错了什么,我是新的,不需要深入了解平台,所以任何和所有的帮助将不胜感激提前感谢马克。
这是我找到的答案感谢Tammy和其他人的所有答案
Ok,这里的交易目标函数从gridview和数据库表中删除文件详细信息,并从存储文件的项目文件夹中删除文件
在gridview的script部分,你想要包含
OnRowDeleting="FuntionName"
不OnSelectedIndexChanged = "FuntionName"
或
OnRowDeleted="FuntionName"
然后在c#代码(codebehind)
protected void FuntionName(object sender, GridViewDeleteEventArgs e)
{
// storing value from cell
TableCell cell = GridView1.Rows[e.RowIndex].Cells[0];
// full path required
string fileName = ("i:/Website/WebSite3/Mag/" + cell.Text);
if(fileName != null || fileName != string.Empty)
{
if((System.IO.File.Exists(fileName)))
{
System.IO.File.Delete(fileName);
}
}
}
只是为了给那些想学习的人提供参考
OnRowDeleting=" functionname "是为删除一行之前,你可以取消删除或运行函数的数据像我做了
OnRowDeleted=" function name "它直接删除
我是这样删除文件的
if ((System.IO.File.Exists(fileName)))
{
System.IO.File.Delete(fileName);
}
还要确保您在删除中传递的文件名是准确的路径
编辑
您也可以使用下面的事件,或者直接使用此代码片段并在方法
中使用void GridView1_SelectedIndexChanged(Object sender, EventArgs e)
{
// Get the currently selected row using the SelectedRow property.
GridViewRow row = CustomersGridView.SelectedRow;
//Debug this line and see what value is returned if it contains the full path.
//If it does not contain the full path then add the path to the string.
string fileName = row.Cells[0].Text
if(fileName != null || fileName != string.empty)
{
if((System.IO.File.Exists(fileName))
System.IO.File.Delete(fileName);
}
}
查看GridView1。SelectedRow不为空:
if (GridView1.SelectedRow == null) return;
string DeleteThis = GridView1.SelectedRow.Cells[0].Text;
在我的项目中,我使用ajax,我在我的代码后面创建一个web方法,就像这样
在前面
$("#attachedfiles a").live("click", function () {
var row = $(this).closest("tr");
var fileName = $("td", row).eq(0).html();
$.ajax({
type: "POST",
url: "SendEmail.aspx/RemoveFile",
data: '{fileName: "' + fileName + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () { },
failure: function (response) {
alert(response.d);
}
});
row.remove();
});
后面代码中的 [WebMethod]
public static void RemoveFile(string fileName)
{
List<HttpPostedFile> files = (List<HttpPostedFile>)HttpContext.Current.Session["Files"];
files.RemoveAll(f => f.FileName.ToLower().EndsWith(fileName.ToLower()));
if (System.IO.File.Exists(HttpContext.Current.Server.MapPath("~/Employee/uploads/" + fileName)))
{
System.IO.File.Delete(HttpContext.Current.Server.MapPath("~/Employee/uploads/" + fileName));
}
}
我想这会对你有帮助。
从路径中删除任何或特定的文件类型(例如".bak")。参见下面的演示代码-
class Program
{
static void Main(string[] args)
{
// Specify the starting folder on the command line, or in
TraverseTree(ConfigurationManager.AppSettings["folderPath"]);
// Specify the starting folder on the command line, or in
// Visual Studio in the Project > Properties > Debug pane.
//TraverseTree(args[0]);
Console.WriteLine("Press any key");
Console.ReadKey();
}
public static void TraverseTree(string root)
{
if (string.IsNullOrWhiteSpace(root))
return;
// Data structure to hold names of subfolders to be
// examined for files.
Stack<string> dirs = new Stack<string>(20);
if (!System.IO.Directory.Exists(root))
{
return;
}
dirs.Push(root);
while (dirs.Count > 0)
{
string currentDir = dirs.Pop();
string[] subDirs;
try
{
subDirs = System.IO.Directory.GetDirectories(currentDir);
}
// An UnauthorizedAccessException exception will be thrown if we do not have
// discovery permission on a folder or file. It may or may not be acceptable
// to ignore the exception and continue enumerating the remaining files and
// folders. It is also possible (but unlikely) that a DirectoryNotFound exception
// will be raised. This will happen if currentDir has been deleted by
// another application or thread after our call to Directory.Exists. The
// choice of which exceptions to catch depends entirely on the specific task
// you are intending to perform and also on how much you know with certainty
// about the systems on which this code will run.
catch (UnauthorizedAccessException e)
{
Console.WriteLine(e.Message);
continue;
}
catch (System.IO.DirectoryNotFoundException e)
{
Console.WriteLine(e.Message);
continue;
}
IEnumerable<FileInfo> files = null;
try
{
//get only .bak file
var directory = new DirectoryInfo(currentDir);
DateTime date = DateTime.Now.AddDays(-15);
files = directory.GetFiles("*.bak").Where(file => file.CreationTime <= date);
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine(e.Message);
continue;
}
catch (System.IO.DirectoryNotFoundException e)
{
Console.WriteLine(e.Message);
continue;
}
// Perform the required action on each file here.
// Modify this block to perform your required task.
foreach (FileInfo file in files)
{
try
{
// Perform whatever action is required in your scenario.
file.Delete();
Console.WriteLine("{0}: {1}, {2} was successfully deleted.", file.Name, file.Length, file.CreationTime);
}
catch (System.IO.FileNotFoundException e)
{
// If file was deleted by a separate application
// or thread since the call to TraverseTree()
// then just continue.
Console.WriteLine(e.Message);
continue;
}
}
// Push the subdirectories onto the stack for traversal.
// This could also be done before handing the files.
foreach (string str in subDirs)
dirs.Push(str);
}
}
}
为更多参考https://msdn.microsoft.com/en-us/library/bb513869.aspx
string sourceDir = @"c:'current";
string backupDir = @"c:'archives'2008";
try
{
string[] picList = Directory.GetFiles(sourceDir, "*.jpg");
string[] txtList = Directory.GetFiles(sourceDir, "*.txt");
// Copy picture files.
foreach (string f in picList)
{
// Remove path from the file name.
string fName = f.Substring(sourceDir.Length + 1);
// Use the Path.Combine method to safely append the file name to the path.
// Will overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true);
}
// Copy text files.
foreach (string f in txtList)
{
// Remove path from the file name.
string fName = f.Substring(sourceDir.Length + 1);
try
{
// Will not overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName));
}
// Catch exception if the file was already copied.
catch (IOException copyError)
{
Console.WriteLine(copyError.Message);
}
}
// Delete source files that were copied.
foreach (string f in txtList)
{
File.Delete(f);
}
foreach (string f in picList)
{
File.Delete(f);
}
}
catch (DirectoryNotFoundException dirNotFound)
{
Console.WriteLine(dirNotFound.Message);
}