当前位置: 代码迷 >> 综合 >> C#将指定文件夹复制粘贴到另外一个文件夹
  详细解决方案

C#将指定文件夹复制粘贴到另外一个文件夹

热度:69   发布时间:2024-01-24 12:42:49.0

 private void button27_Click(object sender, EventArgs e)
{
//@"C:\MP3"需要复制的本地文件路径
//@"D:\MP3" + DateTime.Now.ToString("yyyy-MM-dd")将本地文件粘贴到该目录下
CopyDir(@"C:\MP3", @"D:\MP3" + DateTime.Now.ToString("yyyy-MM-dd"));
}

/// <summary>
/// 复制粘贴本地文件到指定文件夹下
/// </summary>
/// <param name="srcPath">文件本地路径</param>
/// <param name="aimPath">文件复制到该路径下</param>
private void CopyDir(string srcPath, string aimPath)
{

            try
{
//根据文件名筛选
string[] str = new string[] { "73360", "69541", "75962", "69543", "78290", "65887", "63892" };
//string sql = " select * from Table_test ";
DataTable dt = new DataTable();
dt.Columns.Add("tst");
dt.Columns.Add("tst1");
for (int i = 0; i < 7; i++)
{
DataRow dr = dt.NewRow();
dr["tst"] = str[i].ToString();
dr["tst1"] = "2019-06-06";
dt.Rows.Add(dr);
}
// 检查目标目录是否以目录分割字符结束如果不是则添加

                if (aimPath[aimPath.Length - 1] != System.IO.Path.DirectorySeparatorChar)
{

                    aimPath += System.IO.Path.DirectorySeparatorChar;

                }

                // 判断目标目录是否存在如果不存在则新建

                if (!System.IO.Directory.Exists(aimPath))
{

                    System.IO.Directory.CreateDirectory(aimPath);

                }

                // 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组

                // 如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法

                // string[] fileList = Directory.GetFiles(srcPath);

                string[] fileList = System.IO.Directory.GetFileSystemEntries(srcPath);


// 遍历所有的文件和目录
for (int i = 0; i < dt.Rows.Count; i++)
{
foreach (string file in fileList)
{
//获取文件名如:2019-09-09.txt
string filename = System.IO.Path.GetFileName(file).Split('.')[0];
// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
//根据文件名筛选,文件名相同则执行复制粘贴
if (dt.Rows[i]["tst"].ToString() + "_" + dt.Rows[i]["tst1"].ToString().Replace("-", "").Replace("-", "") == filename)
{
if (System.IO.Directory.Exists(file))
{

                                CopyDir(file, aimPath + System.IO.Path.GetFileName(file));

                            }

                            // 否则直接Copy文件

                            else
{
System.IO.File.Copy(file, aimPath + System.IO.Path.GetFileName(file), true);
}

                        }

                    }
}

            }

            catch (Exception e)
{

                throw;

            }

        }
}