Получение списка файлов - C#
Формулировка задачи:
Добрый день!
Столкнулся с проблемой при получении списка файлов. Тестировал на флешке с обходом всех подпапок.
Выдает ошибку Отказано в доступе к System Volume Information.
В чем затык именно при обходе подпапок? Если делать поиск с параметром SearchOption.OnlyTopDirectories, то все в принципе работает.
Собственно вот код:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ForTesting
{
class Program
{
static void Main(string[] args)
{
string[] files = Directory.GetFiles(@"G:", "*.txt",SearchOption.AllDirectories);
foreach (string file in files)
{
Console.WriteLine(file);
}
}
}
}Решение задачи: «Получение списка файлов»
textual
Листинг программы
using System;
using System.Collections.Generic;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var Result = GetFiles(@"J:", "*.txt");
foreach (string file in Result)
{
Console.WriteLine(file);
}
Console.ReadKey();
}
public static IEnumerable<string> GetFiles(string root, string searchPattern)
{
Stack<string> pending = new Stack<string>();
pending.Push(root);
while (pending.Count != 0)
{
var path = pending.Pop();
string[] next = null;
try
{
next = Directory.GetFiles(path, searchPattern);
}
catch { }
if (next != null && next.Length != 0)
foreach (var file in next) yield return file;
try
{
next = Directory.GetDirectories(path);
foreach (var subdir in next) pending.Push(subdir);
}
catch { }
}
}
}
}