C#學習記錄9——Streams資料流

來源:互聯網
上載者:User

標籤:

C#中資料流的功能非常的多,在檔案夾瀏覽目錄,讀入寫出檔案,非同步IO,非同步網路編程等都可以用到

1. 遞迴顯示目錄

 1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Text; 5  6 namespace StreamTester 7 { 8     class Tester 9     {10         static int dirCounter = 1;11         static int indentLevel = -1;12 13         public static void Main()14         {15             Tester t = new Tester();16 17             // 選擇根目錄18             string theDirectory =19             Environment.GetEnvironmentVariable("SystemRoot");20             // 如果是在unix linux 等其他系統下,要加下面一句話21             //string theDirectory = "/tmp";22 23             //下面調用方法來瀏覽該目錄,顯示資料及子目錄24 25             DirectoryInfo dir = new DirectoryInfo(theDirectory);26 27             t.ExploreDirectory(dir);28 29             Console.WriteLine(30                 "\n\n{0} directories found.\n",31                 dirCounter);32         }33 34         // 只要找到一個目錄就遞迴的遞迴的調用自己35 36         private void ExploreDirectory(DirectoryInfo dir)37         {38             indentLevel++; // 目錄層次++39 40             for (int i = 0; i < indentLevel; i++)41                 Console.Write(" "); 42 43             Console.WriteLine("[{0}] {1} [{2}]\n",44                 indentLevel, dir.Name, dir.LastAccessTime);45 46             // 得到dir下的所有子目錄存入directories[]中47             DirectoryInfo[] directories = dir.GetDirectories();48             foreach (DirectoryInfo newDir in directories)49             {50                 dirCounter++;51                 ExploreDirectory(newDir); // 遞迴調用52             }53             indentLevel--; //目錄層次--54         }55     }56 }

結果

上面結果中,放括弧中就是目錄的層級。在代碼中是通過indentLevel來實現的。

注意,真正使用時,應該使用try,catch。原因是,這裡有一個可預測/難以避免的問題:對檔案夾的存取權限。不加try啟動並執行話,遇到無法訪問的檔案夾時,會出現exception停止運行。

2.對檔案進行讀寫操作

 1         private void Run() 2         { 3             // 開啟檔案 4             FileInfo theSourceFile = new FileInfo( 5                 @"C:\Users\shanyuwang\Desktop\test.txt"); 6  7             // 建立text reader 8             StreamReader reader = theSourceFile.OpenText(); 9 10             // 建立text writer11             StreamWriter writer = new StreamWriter(12                 @"C:\Users\shanyuwang\Desktop\test2.txt", false);13 14             string text;15 16             // 每次讀入一行並寫入text,writer17             do18             {19                 text = reader.ReadLine();20                 writer.WriteLine(text);21                 Console.WriteLine(text);22             } while (text != null);23 24             // 關閉檔案。建議養成的好習慣,避免在後續程式中對檔案誤操作25             reader.Close();26             writer.Close();27         }

結果 test2.txt中內容與test.txt中相同。

同樣要注意,reader和writer的路徑是否有效

3.讀入網頁內容

 1 public class Client 2     { 3         static public void Main(string[] Args) 4         { 5             // http request請求 6             HttpWebRequest webRequest = 7                 (HttpWebRequest)WebRequest.Create 8                     ("http://www.baidu.com/"); 9 10             // httq response11             HttpWebResponse webResponse =12                 (HttpWebResponse)webRequest.GetResponse();13 14             // 對response的返回內容讀入15             StreamReader streamReader = new StreamReader(16                 webResponse.GetResponseStream(), Encoding.ASCII);17 18             try19             {20                 string outputString;21                 outputString = streamReader.ReadToEnd();22                 Console.WriteLine(outputString);23             }24             catch25             {26                 Console.WriteLine("Exception reading from web page");27             }28             streamReader.Close();29             Console.ReadKey();30         }31     }

可以發現返回的結果是html檔案。

注意的還是request的網址是否有效或內否達到(youtube等會有exception)

 

從上面的例子中可以非常容易地看出,要常注意指向路徑是否有效,常用try catch

C#學習記錄9——Streams資料流

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.