C# Access Directory

Discussion in 'С/С++, C#, Rust, Swift, Go, Java, Perl, Ruby' started by Sharper, 18 Mar 2010.

  1. Sharper

    Sharper New Member

    Joined:
    10 Mar 2010
    Messages:
    30
    Likes Received:
    1
    Reputations:
    0
    Здравствуйте, стоит такая задача, которую надо реализовать на C#:
    Нахождение файла в Директории «C:\Documents and Settings» .
    Code:
    DirectoryInfo dir = new DirectoryInfo(“C:\Documents and Settings”);
         foreach (FileInfo file in dir.GetFiles(n_file, SearchOption.AllDirectories))
         {
         	Console.WriteLine(file.FullName);
         }
     
    Но в папке C:\Documents and Settings есть папки которые закрыты для чтения когда цыкл доходит до этой папки он выкидывает в catch .
    Как сделать чтоб пропустило папку для чтение и цыкл пошол дальше.
     
    #1 Sharper, 18 Mar 2010
    Last edited: 18 Mar 2010
  2. gold-goblin

    gold-goblin Elder - Старейшина

    Joined:
    26 Mar 2007
    Messages:
    917
    Likes Received:
    174
    Reputations:
    3
    Обработать событие catch. Как сделать на шарпе хз..
     
  3. noxjoker

    noxjoker Member

    Joined:
    7 Aug 2009
    Messages:
    189
    Likes Received:
    24
    Reputations:
    0
    gold-goblin тут проблема в том, что catch выкинет с цикла ... Я сам не знаю... но есть такой вариант.

    Code:
    class Program
    {
    
        static void Main(string[] args)
        {
            ViewDirectory("C:\\Documents and Settings\\");
            Console.Read();
        }
        static void ViewDirectory(string path)
        {
            try
            {
                DirectoryInfo dirs = new DirectoryInfo(path);
                foreach (DirectoryInfo dir in dirs.GetDirectories())
                {
                    Console.WriteLine(dir.ToString());
                    ViewDirectory(dir);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("\tWarn. Path: {0}", path);
            }
        }
    }
    Мне тоже интересно ищо варианты...
     
  4. Sharper

    Sharper New Member

    Joined:
    10 Mar 2010
    Messages:
    30
    Likes Received:
    1
    Reputations:
    0
    noxjoker мне этот код не очень подходит... Метод за пускает самого себя ...

    Хорошо а может кто знает как получить список папок закрытых для чтения .... Зарание спасибо ....
     
  5. nitr0

    nitr0 Elder - Старейшина

    Joined:
    13 Mar 2007
    Messages:
    32
    Likes Received:
    10
    Reputations:
    -3
    А если так?
    PHP:
    DirectoryInfo dir = new DirectoryInfo(“C:\Documents and Settings”);
    foreach (
    FileInfo file in dir.GetFiles(n_file,SearchOption.AllDirectories))
    {
    try
    {
             
    Console.WriteLine(file.FullName);
    }
    catch
    {
    continue;
    }
    }
     
  6. W!z@rD

    W!z@rD Борец за русский язык

    Joined:
    12 Feb 2006
    Messages:
    973
    Likes Received:
    290
    Reputations:
    43
    >>gold-goblin тут проблема в том, что catch выкинет с цикла ...

    ничего подобного.

    и цикл через "и" пишется.
     
  7. noxjoker

    noxjoker Member

    Joined:
    7 Aug 2009
    Messages:
    189
    Likes Received:
    24
    Reputations:
    0
    >>gold-goblin тут проблема в том, что catch выкинет с цикла ...

    ничего подобного.

    Что нечего подобного ?

    Code:
     
    DirectoryInfo dir = new DirectoryInfo("C:\\Documents and Settings\\");
            foreach (FileInfo file in dir.GetFiles("wand.dat", SearchOption.AllDirectories))
            {
                try
                {
                    Console.WriteLine(file.FullName);
                }
                catch
                {
                    // Когда он дойдет до папки которая закрыта для чтения в этот catch оно не попадет!
                }
            }
    
    [​IMG]


    Code:
    DirectoryInfo dir = new DirectoryInfo("C:\\Documents and Settings\\");
            try
            {
                foreach (FileInfo file in dir.GetFiles("wand.dat", SearchOption.AllDirectories))
                {
                    Console.WriteLine(file.FullName);
                }
            }
            catch
            {
                // Когда он доходит до папки которая закрыта для чтения он попадает в catch и цыкл не продолжается.
            }
    
    [​IMG]

    Делаем вывод что catch не поможет.
     
  8. W!z@rD

    W!z@rD Борец за русский язык

    Joined:
    12 Feb 2006
    Messages:
    973
    Likes Received:
    290
    Reputations:
    43
    здравствуйте дорогая редакция

    PHP:
    private static List<stringGetDirs(DirectoryInfo dir)
            {
                List<
    stringad = new List<string>();
                try
                {
                    foreach (var 
    directory in dir.GetDirectories())
                    {
                        
    ad.AddRange(GetDirs(directory));
                    }
                }
                catch (
    UnauthorizedAccessException)
                {
                    
    ad.Add(dir.FullName);
                }
                return 
    ad;
            }

            static 
    void Main(string[] args)
            {
                
    DirectoryInfo dir = new DirectoryInfo("C:\\Documents and Settings\\");
                List<
    stringresult GetDirs(dir);
                foreach (var 
    s in result)
                {
                    
    Console.WriteLine(s);
                }
                
    Console.ReadKey();
            }
    делаем соответствующие выводы.

    учите русский, смешно смотреть на ваши безграмотные посты.

    P.S. зачетно на скринах замазал инфу
    [​IMG]
     
    #8 W!z@rD, 19 Mar 2010
    Last edited: 19 Mar 2010
  9. 0kt0ber

    0kt0ber Member

    Joined:
    28 Jan 2010
    Messages:
    15
    Likes Received:
    5
    Reputations:
    0
    Code:
    using System;
    using System.Collections.Generic;
    using System.IO;
    
    class Program
    {
         static void Main()
        {
               // Get all files in Documents
                List<string> dirs = FileHelper.GetFilesRecursive(@"C:\Temp");
                foreach (string p in dirs)
                {
                    Console.WriteLine(p);
                }
                // Write count
                Console.WriteLine("Count: {0}", dirs.Count);
                Console.Read();
            }
        }
    
        static class FileHelper
        {
            public static List<string> GetFilesRecursive(string b)
            {
                // 1.
                // Store results in the file results list.
                List<string> result = new List<string>();
    
                // 2.
                // Store a stack of our directories.
                Stack<string> stack = new Stack<string>();
    
                // 3.
                // Add initial directory.
                stack.Push(b);
    
                // 4.
                // Continue while there are directories to process
                while (stack.Count > 0)
                {
                    // A.
                    // Get top directory
                    string dir = stack.Pop();
    
                    try
                    {
                        // B
                        // Add all files at this directory to the result List.
                        result.AddRange(Directory.GetFiles(dir, "*.*"));
    
                        // C
                        // Add all directories at this directory.
                        foreach (string dn in Directory.GetDirectories(dir))
                        {
                            stack.Push(dn);
                        }
                    }
                    catch
                    {
                        // D
                        // Could not open the directory
                    }
                }
                return result;
            }
        }
    Тут