繁体   English   中英

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

[英]SQL query for selecting directory and then deleting all files within it - C#

我需要删除目录中的所有文件(由于图库脚本会保留完整尺寸的图像,但未使用它们!)。

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

任何想法,我很沮丧!

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

首先,在您填充数据集之后,我将立即关闭您的连接字符串。 我会对您的DataTable进行“快速监视”,并确保所有数据都在那里。 如果没有,请修改您的查询。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM