在C#中删除文件夹内的文件

时间:2015-10-07 13:42:18

标签: c# .net

我正在创建应用程序以删除文件超过15天,我使用C#语言创建了一个项目"多线程"能够删除这些文件,但它只能读取带有错误的第一个文件

  

目录名无效

有人可以帮我吗?

private void process3()
{
    //DirectoryInfo info1 = new DirectoryInfo(@"\\10.4.9.202\d\PapyrusRes\appdata\");
    DirectoryInfo info1 = new DirectoryInfo(@"\\DXB-RASO-MCH\Users\oalahmad\Dropbox\backup\Backup5\Desktop\New folder2");
    // long Size = 0;

    //C:\Users\oalahmad\Dropbox\backup\Backup5\Desktop\New folder2
    String[] filePaths = (from fls in info1.EnumerateFiles()
                          where (fls.LastWriteTime.Date < DateTime.Today.AddDays(-15))
                          select fls.FullName).ToArray();

    int i = 0;

    if (!File.Exists(logPath3))
    {
        // Create a file to write to. 
        using (StreamWriter sw = File.CreateText(logPath3))
        {
            sw.WriteLine("Deletion Process History:");
            sw.WriteLine(" ");
            sw.WriteLine(" ");
        }
    }
    //stopwatch.Start();
    try
    {
        foreach (String f in filePaths)
        {
            DirectoryInfo info = new DirectoryInfo(f);
            int difference = DateTime.Today.Subtract(info.LastWriteTime).Days;

            textBox2.BeginInvoke(new Action(() =>
                {
                    textBox2.Text  += "Folder Name: " + Path.GetFileName(f) + 
                                      "\r\nDate Modified: " + difference + 
                                      "\r\n------\r\n";
                }));

            Thread.Sleep(10);

            i++;

            Directory.Delete(f, true);
            count++;
        }

        using (StreamWriter sw = File.AppendText(logPath3))
        {
            sw.WriteLine("Successful at: " + DateTime.Now + "     " + count + 
                         " files were deleted");
        }
    }
    catch (Exception ex)
    {
        // log errors
        // Write your content here
        using (StreamWriter sw = File.AppendText(logPath3))
        {
            if (count == 0)
                sw.WriteLine("Unsuccessful at: " + DateTime.Now + "            Error: " + 
                             ex.Message);
            else
                sw.WriteLine("Unsuccessful at: " + DateTime.Now + "     " + count + 
                             " files were deleted" + "            Error: " + ex.Message);
        }
    }
}

0 个答案:

没有答案