C# 如何使用asp.net从文件夹中删除特定文件

C# 如何使用asp.net从文件夹中删除特定文件,c#,asp.net,C#,Asp.net,这里的交易我得到了一个叫做gridview1的datagridviewer和一个fileupload1,当我上传一个文件时,它用文件名和路径更新数据库中的gridview1和表,并将所述文件存储在文件夹“Mag”。。。但是现在我想做的是相反的,我得到了如何使用gridview删除表条目,但是从文件夹“Mag”中删除文件不起作用。我在C#或codebehind中使用了以下代码 protected void GridView1_Del(object sender, EventArgs e) {

这里的交易我得到了一个叫做gridview1的datagridviewer和一个fileupload1,当我上传一个文件时,它用文件名和路径更新数据库中的gridview1和表,并将所述文件存储在文件夹“Mag”。。。但是现在我想做的是相反的,我得到了如何使用gridview删除表条目,但是从文件夹“Mag”中删除文件不起作用。我在C#或codebehind中使用了以下代码

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

     }
  }
这给了我错误

“对象引用未设置为对象的实例。”

请告诉我我做错了什么我是新的,不需要深入了解平台,所以任何和所有的帮助将不胜感激 提前谢谢 标记

这是我找到的答案谢谢塔米和其他人的回答

确定这里交易目标函数从gridview和数据库表中删除文件详细信息,并从存储文件的项目文件夹中删除文件

在gridview的脚本部分中,您希望包括

OnRowDeleting="FuntionName"
不是

然后是C代码(codebehind)

仅供那些想学习的人参考

onrowdeleding=“FuntionName”用于在删除行之前,您可以取消删除或像我一样对数据运行函数


OnRowDeleted=“FunctionName”它直接删除

检查GridView1.SelectedRow不为空:

if (GridView1.SelectedRow == null) return;
string DeleteThis = GridView1.SelectedRow.Cells[0].Text;

这就是我删除文件的方式

if ((System.IO.File.Exists(fileName)))
                {
                    System.IO.File.Delete(fileName);
}
还要确保在delete中传递的文件名是正确的路径

编辑

您也可以使用以下事件,或者只使用此代码段中的代码并在方法中使用

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

     }
  }

在我的项目中,我使用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));
            }
        }
[WebMethod]
公共静态void RemoveFile(字符串文件名)
{
列表文件=(列表)HttpContext.Current.Session[“文件”];
files.RemoveAll(f=>f.FileName.ToLower().EndsWith(FileName.ToLower());
如果(System.IO.File.Exists(HttpContext.Current.Server.MapPath(“~/Employee/uploads/”+fileName)))
{
System.IO.File.Delete(HttpContext.Current.Server.MapPath(“~/Employee/uploads/”+fileName));
}
}

我认为这将帮助您。

从路径中删除任何或特定的文件类型(例如“.bak”)。
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);
}
请参阅下面的演示代码-

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);
                }
            }
        }
类程序
{
静态void Main(字符串[]参数)
{
//在命令行或中指定起始文件夹
TraverseTree(ConfigurationManager.AppSettings[“folderPath”]);
//在命令行或中指定起始文件夹
//项目>属性>调试窗格中的Visual Studio。
//TraverseTree(args[0]);
Console.WriteLine(“按任意键”);
Console.ReadKey();
}
公共静态void TraverseTree(字符串根)
{
if(string.IsNullOrWhiteSpace(根))
返回;
//用于保存要删除的子文件夹名称的数据结构
//检查文件。
堆栈dirs=新堆栈(20);
如果(!System.IO.Directory.Exists(root))
{
返回;
}
直接推力(根);
而(dirs.Count>0)
{
字符串currentDir=dirs.Pop();
字符串[]子字段;
尝试
{
subDirs=System.IO.Directory.GetDirectories(currentDir);
}
//如果没有,将引发UnauthorizedAccessException异常
//文件夹或文件的发现权限。该权限可能不可接受,也可能不可接受
//忽略异常并继续枚举其余文件和
//DirectoryNotFound异常也是可能的(但不太可能)
//将引发。如果currentDir已被删除,则会发生这种情况
//在我们调用Directory.Exists之后,存在另一个应用程序或线程
//捕获哪些异常的选择完全取决于特定任务
//你打算表演,也取决于你确定知道多少
//关于将在其上运行此代码的系统。
捕获(未经授权的访问例外)
{
控制台写入线(e.Message);
继续;
}
捕获(System.IO.DirectoryNotFounde异常)
{
控制台写入线(e.Message);
继续;
}
IEnumerable files=null;
尝试
{
//仅获取.bak文件
var directory=newdirectoryinfo(currentDir);
DateTime date=DateTime.Now.AddDays(-15);

files=directory.GetFiles(“*.bak”).Where(file=>file.CreationTime)在什么情况下会出现异常?它在哪一行出现异常?
gridview 1.SelectedRow.Cells[0]。Text
对我来说很可疑。这一行是否从代码字符串中删除this=gridview 1.SelectedRow.Cells[0].Text;返回正确的文件路径?几乎所有
NullReferenceException
的情况都相同。请参阅“”对于一些提示。SelectedRow不是一个集合,因此检查它是否为null将是一个更好的提示。在ASP.Net场景中…在删除之前先执行BP。这是ASP.Net场景,文件将不会被使用a时间也是@tammy你会说过程从提到的文件夹中删除文件,还是我必须添加路径?是的,如果我理解co正确地说,您必须将该路径添加到happen@jeremey是的,在我的情况下,它假设该文件不是当前使用的,但我同意
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);
}
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);
                }
            }
        }