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

后端 未结 5 613
感情败类
感情败类 2021-02-01 21:12

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 pa

相关标签:
5条回答
  • 2021-02-01 21:20

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

    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

    0 讨论(0)
  • 2021-02-01 21:24

    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);
    
         }
      }
    
    0 讨论(0)
  • 2021-02-01 21:24

    Check the GridView1.SelectedRow is not null:

    if (GridView1.SelectedRow == null) return;
    string DeleteThis = GridView1.SelectedRow.Cells[0].Text;
    
    0 讨论(0)
  • 2021-02-01 21:30

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

    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.

    0 讨论(0)
  • 2021-02-01 21:32
    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);
    }
    
    0 讨论(0)
提交回复
热议问题