標籤:style blog http io ar color os sp for
本人初學C#,最近才接觸數組、流,編寫了一個小程式。幾乎沒實用價值,只用來記錄自己所學。
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.IO; 6 namespace namespace1 //命名空間 7 { 8 class Program 9 {10 static void Main(string[] args)11 {12 FileStream file = File.Open("F:/filename.txt"/*初始檔案路徑*/, FileMode.Open, FileAccess.Read);//開啟初始檔案13 FileStream file2 = File.Open("F:/filename2.txt"/*過濾後檔案*/, FileMode.Create, FileAccess.Write);//建立處理後的檔案14 file2.Close();//關閉file2檔案流15 byte[] array = new byte[file.Length];//初始化位元組數組16 file.Read(array, 0, array.Length);//讀取流中的資料並把它寫入位元組數組中17 file.Close(); //關閉file1檔案流 18 string str = Encoding.Default.GetString(array); //將位元組數組轉化為字串19 char[] ch = str.ToCharArray(); //將字串轉化為字元數組20 string str1 = ""; 21 foreach (char c in ch) //遍曆ch 22 {23 if ((c != ‘1‘) & (c != ‘2‘) & (c != ‘3‘) & (c != ‘4‘) & (c != ‘5‘) & (c != ‘6‘) & (c != ‘7‘) & (c != ‘8‘) & (c != ‘9‘) & (c != ‘0‘))24 //判斷字元不等於數字,可根據實際情況更改過濾條件 25 {26 str1 = str1 + c.ToString();//字串拼接27 }28 }29 string fullPath = "F:/filename2.txt"; //將字串寫入檔案30 if (System.IO.File.Exists(fullPath)) 31 {32 using (StreamWriter sw = new StreamWriter(fullPath, false, Encoding.Default)) 33 {34 sw.WriteLine(str1); 35 } 36 }37 }38 }39 }
View Code
C#實現文字檔字元過濾