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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14251220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:10:29  来源:igfitidea点击:

How to delete a specific file from folder using asp.net

c#asp.net

提问by Mark

here's the deal I got a datagridviewer which is called gridview1 and a fileupload1 when i upload a file it updates the gridview1 and table in database with the file name and path and stores the said file in folder "Mag"... but now what i want to do is the reverse i got how to use the gridview to delete the table entry but deleting the file from folder "Mag" is not working have used the following code in C# or codebehind

这是交易我得到了一个名为 gridview1 的 datagridviewer 和一个 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);
        }
    }
}

it gives me error

它给了我错误

"Object reference not set to an instance of an object."

“你调用的对象是空的。”

pls tell me what im doing wrong am new and don't have to in depth understanding of the platform so any and all help will be appreciated thanks in advance Mark

请告诉我我做错了什么我是新手,不必深入了解平台,因此任何和所有帮助都将不胜感激,提前感谢马克

Here is the answer i found Thanks Tammy and everyone else for all the answers

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

Ok here the deal target function delete file details from gridview and database table and file from project folder where the file is stored

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

in script section of gridview you would want to include

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

OnRowDeleting="FuntionName"

Not

不是

OnSelectedIndexChanged = "FuntionName"

or

或者

OnRowDeleted="FuntionName"

then in C# code(codebehind)

然后在 C# 代码中(代码隐藏)

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

     }
  }

And just for added reference for those who want to learn

仅供想学习的朋友参考

OnRowDeleting="FuntionName" is for just before deleting a row you can cancel deleting or run functions on the data like i did

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

OnRowDeleted="FuntionName" it directly deletes

OnRowDeleted="FuntionName" 直接删除

采纳答案by tam tam

This is how I delete files

这就是我删除文件的方式

if ((System.IO.File.Exists(fileName)))
                {
                    System.IO.File.Delete(fileName);
}

Also make sure that the file name you are passing in your delete, is the accurate path

还要确保您在删除时传递的文件名是准确的路径

EDIT

编辑

You could use the following event instead as well or just use the code in this snippet and use in your method

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

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

     }
  }

回答by Jeremy Thompson

Check the GridView1.SelectedRow is not null:

检查 GridView1.SelectedRow 不为空:

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

回答by Rajpurohit

In my project i am using ajax and i create a web method in my code behind like this

在我的项目中,我使用 ajax,并在我的代码中创建了一个 web 方法,就像这样

in front

在前

 $("#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();
        });  

in code behind

在后面的代码中

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

i think this will help you.

我想这会帮助你。

回答by Ali Najaf Zadeh

string sourceDir = @"c:\current";
string backupDir = @"c:\archives08";

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

回答by Ravindra Vairagi

Delete any or specific file type(for example ".bak") from a path. See demo code below -

从路径中删除任何或特定文件类型(例如“.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);
                }
            }
        }

for more reference - https://msdn.microsoft.com/en-us/library/bb513869.aspx

更多参考 - https://msdn.microsoft.com/en-us/library/bb513869.aspx