SQL查询选择目录,然后删除其中的所有文件- c#。

时间:2023-01-13 20:18:44

I need to delete all files in a directory (due to a gallery script that is keeping full size images but not using them!).

我需要删除一个目录中的所有文件(由于一个gallery脚本,它保存了完整大小的图像,但不使用它们!)

I've written a bit of code that dumps the query into a DataTable and then loops through the records. However, when I introduce the loop for finding all files and deleting them it only seems to run for the first SiteID. There should be at least 350 directories to scan, but it only does the first SiteID (all the modules within this SiteID).

我编写了一些代码,将查询转储到一个DataTable中,然后循环遍历这些记录。但是,当我引入循环查找所有文件并删除它们时,它似乎只运行在第一个SiteID中。应该有至少350个目录来扫描,但它只执行第一个SiteID(这个SiteID中的所有模块)。

Any ideas as I'm stumped!

我被难住了!

private void frmMain_Load(object sender, EventArgs e)
{
    SqlConnection con = null;
    try
    {
        // Open connection to the database
        string ConnectionString = "server=(local);UID=x;PWD=y;database=mojoportal2";
        con = new SqlConnection(ConnectionString);
        con.Open();

        SqlDataAdapter da = new SqlDataAdapter();
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();

        da.SelectCommand = new SqlCommand(@"SELECT SiteID, ModuleID FROM mp_Modules where ModuleDefID = 16 ORDER By SiteID DESC", con);
        da.Fill(ds, "Sites");
        dt = ds.Tables["Sites"];

        foreach (DataRow dr in dt.Rows)
        {
            string SiteID = dr["SiteID"].ToString();
            string ModuleID = dr["ModuleID"].ToString();
            string directoryPath = @"E:\Website\" + SiteID + @"\media\GalleryImages\" + ModuleID + @"\FullSizeImages";

            MessageBox.Show("Deleting Files In " + directoryPath);

            string[] files = Directory.GetFiles(directoryPath);
            string[] dirs = Directory.GetDirectories(directoryPath);

            foreach (string file in files)
            {
                MessageBox.Show(file);
                //File.SetAttributes(file, FileAttributes.Normal);
                //File.Delete(file);
            }
        }
    }
    catch (Exception ex)
    {
        // Print error message
        MessageBox.Show(ex.Message);
    }
    finally
    {
        if (con.State == ConnectionState.Open)
            con.Close();
    }
}

1 个解决方案

#1


0  

First I would close your connection string right after you fill your DataSet. I would take a 'Quick Watch' at your DataTable and make sure all of your data is there. If its not then modify your query.

首先,在您填充数据集之后,我将关闭您的连接字符串。我会在你的数据表上快速看一看,确保你所有的数据都在那里。如果它没有修改您的查询。

#1


0  

First I would close your connection string right after you fill your DataSet. I would take a 'Quick Watch' at your DataTable and make sure all of your data is there. If its not then modify your query.

首先,在您填充数据集之后,我将关闭您的连接字符串。我会在你的数据表上快速看一看,确保你所有的数据都在那里。如果它没有修改您的查询。