1 private void Replace(string oldStr, string newStr, string file) 2 { 3 FileStream fs = File.OpenRead(file); 4 //to know if this file is text file or binary file 5 byte b; 6 for (long i = 0; i < fs.Length; i++) 7 { 8 b = (byte)fs.ReadByte(); 9 if (b == 0) 10 { 11 MessageBox.Show("Not Text File"); 12 return;//if there is this byte then this is not text file。 13 } 14 } 15 //Judge the type of encoding。 16 byte[] bytes = new byte[2]; 17 Encoding coding = Encoding.Default; 18 if (fs.Read(bytes, 0, 2) > 2) 19 { 20 if (bytes == new byte[2] { 0xFF, 0xFE }) coding = Encoding.Unicode; 21 if (bytes == new byte[2] { 0xFE, 0xFF }) coding = Encoding.BigEndianUnicode; 22 if (bytes == new byte[2] { 0xEF, 0xBB }) coding = Encoding.UTF8; 23 } 24 fs.Close(); 25 26 string text = File.ReadAllText(file,coding); 27 File.WriteAllText(file, text.Replace(oldStr, newStr), coding); 28 }
时间: 2024-11-08 03:17:58