<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # 如何:循環訪問目錄樹(C# 編程指南) 詞組“循環訪問目錄樹”的意思是在指定的根文件夾下,訪問每個嵌套子目錄中任意深度的所有文件。您不必打開每一個文件。可以只檢索 **string** 形式的文件名或子目錄名,或者可以檢索 [System.IO.FileInfo](https://msdn.microsoft.com/zh-cn/library/system.io.fileinfo.aspx) 或 [System.IO.DirectoryInfo](https://msdn.microsoft.com/zh-cn/library/system.io.directoryinfo.aspx) 對象形式的其他信息。 | ![](https://box.kancloud.cn/2016-01-31_56adb62c1380a.jpg) 注意 | | :-- | | 在 Windows 中,可交換使用術語“目錄”和“文件夾”。大多數文檔和用戶界面文本使用術語“文件夾”,但 .NET Framework 類庫使用術語“目錄”。 | 最簡單的例子,如果您確信您擁有指定根目錄下所有目錄的訪問權限,則您可以使用 System.IO.SearchOption.AllDirectories 標志。該標志返回與指定模式相匹配的所有嵌套子目錄。下面的示例演示如何使用該標志。 ``` root.GetDirectories("*.*", System.IO.SearchOption.AllDirectories); ``` 此方法的缺點是,如果指定根目錄下任何一個子目錄引發了 [DirectoryNotFoundException](https://msdn.microsoft.com/zh-cn/library/system.io.directorynotfoundexception.aspx) 或 [UnauthorizedAccessException](https://msdn.microsoft.com/zh-cn/library/system.unauthorizedaccessexception.aspx),則整個方法將會失敗并且不返回任何目錄。使用 [GetFiles](https://msdn.microsoft.com/zh-cn/library/4cyf24ss.aspx) 方法時也是如此。如果一定要處理特定子文件夾中的這些異常,則必須手動遍歷該目錄樹,如下面的示例所示。 手動遍歷目錄樹時,可以先處理子目錄(前序遍歷),或者可以先處理文件(后序遍歷)。如果執行前序遍歷,則在循環訪問直接位于當前文件夾本身中的文件之前,請先遍歷當前文件夾下的整個樹。本文檔后面的示例執行的是后序遍歷,但您可以輕松地將它們修改為執行前序遍歷。 另外還可以選擇是使用遞歸遍歷,還是使用基于堆棧的遍歷。本文檔后面的示例對這兩種方法進行了演示。 如果必須對文件和文件夾上執行各種操作,則可以通過下面的方法將這些示例模塊化:將操作重構到單獨的函數,這樣您就可以通過單個委托來調用這些函數。 | ![](https://box.kancloud.cn/2016-01-31_56adb62c1380a.jpg) 注意 | | :-- | | NTFS 文件系統可以包含交接點、符號鏈接和硬鏈接形式的重新分析點。.NET Framework 方法(如 [GetFiles](https://msdn.microsoft.com/zh-cn/library/4cyf24ss.aspx) 和 [GetDirectories](https://msdn.microsoft.com/zh-cn/library/s7xk2b58.aspx))將不返回重新分析點下的任何子目錄。此行為可防止兩個重新分析點相互引用時陷入無限循環。通常,為了確保您不會無意修改或刪除文件,在使用重新分析點時應特別小心。如果需要精確控制重新分析點,請使用平臺調用或本機代碼直接調用相應的 Win32 文件系統方法。 | 下面的示例演示如何使用遞歸遍歷目錄樹。遞歸方法很簡潔,但如果目錄樹很大且嵌套很深,則有可能會引起堆棧溢出異常。 對于所處理的特定異常以及在每個文件和文件夾上執行的特定操作,都只是作為示例提供。您應該修改此代碼來滿足自己特定的需要。有關更多信息,請參見代碼中的注釋。 ``` public class RecursiveFileSearch { static System.Collections.Specialized.StringCollection log = new System.Collections.Specialized.StringCollection(); static void Main() { // Start with drives if you have to search the entire computer. string[] drives = System.Environment.GetLogicalDrives(); foreach (string dr in drives) { System.IO.DriveInfo di = new System.IO.DriveInfo(dr); // Here we skip the drive if it is not ready to be read. This // is not necessarily the appropriate action in all scenarios. if (!di.IsReady) { Console.WriteLine("The drive {0} could not be read", di.Name); continue; } System.IO.DirectoryInfo rootDir = di.RootDirectory; WalkDirectoryTree(rootDir); } // Write out all the files that could not be processed. Console.WriteLine("Files with restricted access:"); foreach (string s in log) { Console.WriteLine(s); } // Keep the console window open in debug mode. Console.WriteLine("Press any key"); Console.ReadKey(); } static void WalkDirectoryTree(System.IO.DirectoryInfo root) { System.IO.FileInfo[] files = null; System.IO.DirectoryInfo[] subDirs = null; // First, process all the files directly under this folder try { files = root.GetFiles("*.*"); } // This is thrown if even one of the files requires permissions greater // than the application provides. catch (UnauthorizedAccessException e) { // This code just writes out the message and continues to recurse. // You may decide to do something different here. For example, you // can try to elevate your privileges and access the file again. log.Add(e.Message); } catch (System.IO.DirectoryNotFoundException e) { Console.WriteLine(e.Message); } if (files != null) { foreach (System.IO.FileInfo fi in files) { // In this example, we only access the existing FileInfo object. If we // want to open, delete or modify the file, then // a try-catch block is required here to handle the case // where the file has been deleted since the call to TraverseTree(). Console.WriteLine(fi.FullName); } // Now find all the subdirectories under this directory. subDirs = root.GetDirectories(); foreach (System.IO.DirectoryInfo dirInfo in subDirs) { // Resursive call for each subdirectory. WalkDirectoryTree(dirInfo); } } } } ``` 下面的示例演示在不使用遞歸的情況下如何循環訪問目錄樹中的文件和文件夾。該技術使用泛型 [Stack&lt;T&gt;](https://msdn.microsoft.com/zh-cn/library/3278tedw.aspx) 集合類型,該類型是一個后進先出 (LIFO) 堆棧。 對于所處理的特定異常以及在每個文件和文件夾上執行的特定操作,都只是作為示例提供。您應該修改此代碼來滿足自己特定的需要。有關更多信息,請參見代碼中的注釋。 ``` public class StackBasedIteration { static void Main(string[] args) { // Specify the starting folder on the command line, or in // Visual Studio in the Project > Properties > Debug pane. TraverseTree(args[0]); Console.WriteLine("Press any key"); Console.ReadKey(); } public static void TraverseTree(string root) { // Data structure to hold names of subfolders to be // examined for files. Stack<string> dirs = new Stack<string>(20); if (!System.IO.Directory.Exists(root)) { throw new ArgumentException(); } dirs.Push(root); while (dirs.Count > 0) { string currentDir = dirs.Pop(); string[] subDirs; try { subDirs = System.IO.Directory.GetDirectories(currentDir); } // An UnauthorizedAccessException exception will be thrown if we do not have // discovery permission on a folder or file. It may or may not be acceptable // to ignore the exception and continue enumerating the remaining files and // folders. It is also possible (but unlikely) that a DirectoryNotFound exception // will be raised. This will happen if currentDir has been deleted by // another application or thread after our call to Directory.Exists. The // choice of which exceptions to catch depends entirely on the specific task // you are intending to perform and also on how much you know with certainty // about the systems on which this code will run. catch (UnauthorizedAccessException e) { Console.WriteLine(e.Message); continue; } catch (System.IO.DirectoryNotFoundException e) { Console.WriteLine(e.Message); continue; } string[] files = null; try { files = System.IO.Directory.GetFiles(currentDir); } catch (UnauthorizedAccessException e) { Console.WriteLine(e.Message); continue; } catch (System.IO.DirectoryNotFoundException e) { Console.WriteLine(e.Message); continue; } // Perform the required action on each file here. // Modify this block to perform your required task. foreach (string file in files) { try { // Perform whatever action is required in your scenario. System.IO.FileInfo fi = new System.IO.FileInfo(file); Console.WriteLine("{0}: {1}, {2}", fi.Name, fi.Length, fi.CreationTime); } catch (System.IO.FileNotFoundException e) { // If file was deleted by a separate application // or thread since the call to TraverseTree() // then just continue. Console.WriteLine(e.Message); continue; } } // Push the subdirectories onto the stack for traversal. // This could also be done before handing the files. foreach (string str in subDirs) dirs.Push(str); } } } ``` 通常,測試每個文件夾以確定您的應用程序是否有權限打開它是非常耗時的。因此,代碼示例只是將該部分操作放到了一個 **try/catch** 塊內。您可以修改該 **catch** 塊,以便在訪問某個文件夾遭受拒絕時,您可以提升自己的權限,然后再次訪問它。通常,只捕捉那些無需使應用程序停留在一個未知狀態就可以處理的異常。 如果必須將目錄樹的內容存儲到內存或磁盤中,則最好只存儲每個文件的 [FullName](https://msdn.microsoft.com/zh-cn/library/system.io.filesysteminfo.fullname.aspx) 屬性(**string** 類型)。然后,可以根據需要使用該字符串創建一個新的 [FileInfo](https://msdn.microsoft.com/zh-cn/library/system.io.fileinfo.aspx) 或 [DirectoryInfo](https://msdn.microsoft.com/zh-cn/library/system.io.directoryinfo.aspx) 對象,或者打開任何需要進行其他處理的文件。 ## 可靠編程 可靠文件迭代代碼必須考慮文件系統的諸多復雜性。有關更多信息,請參見 [NTFS Technical Reference](http://go.microsoft.com/fwlink/?LinkId=79488)(NTFS 技術參考)。 ## 請參閱 [System.IO](https://msdn.microsoft.com/zh-cn/library/system.io.aspx) [LINQ and File Directories](https://msdn.microsoft.com/zh-cn/library/bb397911.aspx) [文件系統和注冊表(C# 編程指南)](https://msdn.microsoft.com/zh-cn/library/2kzb96fk.aspx)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看