爲文件提供 Stream,既支持同步讀寫操做,也支持異步讀寫操做。android
1 using System; 2 using System.IO; 3 using System.Text; 4 5 class Test 6 { 7 8 public static void Main() 9 { 10 string path = @"c:\temp\MyTest.txt"; 11 12 // Delete the file if it exists. 13 if (File.Exists(path)) 14 { 15 File.Delete(path); 16 } 17 18 //Create the file. 19 using (FileStream fs = File.Create(path)) 20 { 21 AddText(fs, "This is some text"); 22 AddText(fs, "This is some more text,"); 23 AddText(fs, "\r\nand this is on a new line"); 24 AddText(fs, "\r\n\r\nThe following is a subset of characters:\r\n"); 25 26 for (int i=1;i < 120;i++) 27 { 28 AddText(fs, Convert.ToChar(i).ToString()); 29 30 } 31 } 32 33 //Open the stream and read it back. 34 using (FileStream fs = File.OpenRead(path)) 35 { 36 byte[] b = new byte[1024]; 37 UTF8Encoding temp = new UTF8Encoding(true); 38 while (fs.Read(b,0,b.Length) > 0) 39 { 40 Console.WriteLine(temp.GetString(b)); 41 } 42 } 43 } 44 45 private static void AddText(FileStream fs, string value) 46 { 47 byte[] info = new UTF8Encoding(true).GetBytes(value); 48 fs.Write(info, 0, info.Length); 49 } 50 }
CanRead | 獲取一個值,該值指示當前流是否支持讀取。 |
CanSeek | 獲取一個值,該值指示當前流是否支持查找。 |
CanTimeout | 獲取一個值,該值肯定當前流是否能夠超時。 (Inherited from Stream) |
CanWrite | 獲取一個值,該值指示當前流是否支持寫入。 |
Handle | 獲取當前 |
IsAsync | 獲取一個值,它指示 |
Length | 獲取用字節表示的流長度。 |
Name | 獲取 |
Position | 獲取或設置此流的當前位置。 |
ReadTimeout | 獲取或設置一個值(以毫秒爲單位),該值肯定流在超時前嘗試讀取多長時間。 (Inherited from Stream) |
SafeFileHandle | 獲取 SafeFileHandle 對象,它表明當前 FileStream 對象所封裝的文件的操做系統文件句柄。 |
WriteTimeout | 獲取或設置一個值(以毫秒爲單位),該值肯定流在超時前嘗試寫入多長時間。 (Inherited from Stream) |
IDisposable.Dispose() | 釋放由 Stream 使用的全部資源。 (Inherited from Stream) |