2013-11-11 5 views
0

Мне нужно подсчитать количество файлов, удаленных в этой рекурсивной функции. Поскольку он рекурсивный, я не могу использовать операторы if, а C# не поддерживает глобальные переменные. Любые альтернативы?Счетчик внутри рекурсивной функции

static void DirSearch(string path) 
{ 
    try 
    { 
     foreach (string dirPath in Directory.GetDirectories(path)) 
     { 
      foreach (string filePath in Directory.GetFiles(dirPath)) 
      { 
       string filename = Path.GetFileName(filePath); 
       if (filename.Equals("desktop.txt")) 
       { 
        File.Delete(filePath); 
        //count++ 
       } 
       Console.WriteLine(filePath); // print files 
      } 
      Console.WriteLine(dirPath); // print directories 
      DirSearch(dirPath); 
     } 
    } 
    catch (System.Exception excpt) 
    { 
     Console.WriteLine(excpt.Message); 
    } 
} 
+2

, конечно, C# поддерживает глобальные переменные. где ты понял, что это не так ?! также, когда-либо думал о передаче дополнительного параметра, чтобы сохранить количество удаленных файлов? добавьте дополнительный параметр в свой метод для счетчика. –

+0

@Ahmedilyas Технически это не все они члены того или иного типа. – Lloyd

+0

Как в стороне, я бы переименовал функцию. Поиск подразумевает, что он будет пересекать источник данных и возвращать информацию об этом, но функция удаляет все файлы desktop.txt. Вероятно, также стоит добавить параметр для имени файла, а не жестко-кодировать его на desktop.txt. –

ответ

7

Один из способов - передать что-то для того, чтобы оно могло считаться. Я хотел бы сделать это с помощью ref, например:

static void DirSearch(string path, ref int count) 
{ 
    try 
    { 
     foreach (string dirPath in Directory.GetDirectories(path)) 
     { 
      foreach (string filePath in Directory.GetFiles(dirPath)) 
      { 
       string filename = Path.GetFileName(filePath); 
       if (filename.Equals("desktop.txt")) 
       { 
        File.Delete(filePath); 
        count++ 
       } 
       Console.WriteLine(filePath); // print files 
      } 
      Console.WriteLine(dirPath); // print directories 
      DirSearch(dirPath,ref count); 
     } 
    } 
    catch (System.Exception excpt) 
    { 
     Console.WriteLine(excpt.Message); 
    } 
} 

Затем вызовите его:

int count = 0; 

DirSearch(@"C:\SomePath",ref count); 

Затем вы можете использовать count как обычно, как бы вы прокомментировали в вашем коде.

+0

необходимо передать 'ref count' в качестве аргумента для рекурсивного вызова DirSearch –

+0

@SamPearson К сожалению, у вас не получилось, что вы правы, исправлены. – Lloyd

+2

Почему 'ref', когда вы можете вернуть количество затронутых каталогов? – Romoku

7

Попробуйте рекурсивно count следующим образом. Таким образом, DirSearch возвращает count удаленных файлов.

static int DirSearch(string path) 
{ 
    int count = 0; 

    try 
    { 
     foreach (string dirPath in Directory.GetDirectories(path)) 
     { 
      foreach (string filePath in Directory.GetFiles(dirPath)) 
      { 
       string filename = Path.GetFileName(filePath); 
       if (filename.Equals("desktop.txt")) 
       { 
        File.Delete(filePath); 

        count++; 
       } 
       Console.WriteLine(filePath); // print files 
      } 
      Console.WriteLine(dirPath); // print directories 
      count += DirSearch(dirPath); 
     } 
    } 
    catch (System.Exception excpt) 
    { 
     Console.WriteLine(excpt.Message); 
    } 

    return count; 
} 
1

Без исх переменной (так что вам не нужно что-то передать, что правильно инициализирован):

static int DirSearch(string path) 
{ 
    try 
    { 
     int count = 0; 
     foreach (string dirPath in Directory.GetDirectories(path)) 
     { 
      foreach (string filePath in Directory.GetFiles(dirPath)) 
      { 
       string filename = Path.GetFileName(filePath); 
       if (filename.Equals("desktop.txt")) 
       { 
        File.Delete(filePath); 
        count++; 
       } 
       Console.WriteLine(filePath); // print files 
      } 
      Console.WriteLine(dirPath); // print directories 
      count += DirSearch(dirPath); 
     } 
     return count; 
    } 
    catch (System.Exception excpt) 
    { 
     Console.WriteLine(excpt.Message); 
    } 
} 
Смежные вопросы