日期:2014-05-17 浏览次数:21498 次
namespace FileStreamDemo { class Program { static void Main(string[] args) { byte[] m_byteData = new byte[100]; char[] m_charData = new char[100]; byte[] bytedata = new byte[100]; try { //创建F:\example.txt的FileStream对象 FileStream filestream = new FileStream(@"F:\example.txt", FileMode.OpenOrCreate); //将要写入的字符串转换成字符数组 m_charData = "My first file operation".ToCharArray(); //通过UTF-8编码方法将字符数组转换成字节数组 Encoder encode = Encoding.UTF8.GetEncoder(); encode.GetBytes(m_charData, 0, m_charData.Length, m_byteData, 0, true); //将流的当前位置设为文件开始位置 filestream.Seek(0, SeekOrigin.Begin); //将字节数组中的内容写入文件 filestream.Write(m_byteData, 0, m_byteData.Length); filestream.Flush(); //这句很重要,刷新,才能将内存中的数据真正的写入文件中 filestream.Close(); Console.WriteLine("write to file Succeed!"); FileStream readstream = new FileStream(@"F:\example.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); readstream.Seek(0, SeekOrigin.Begin); readstream.Read(bytedata, 0, 100); Decoder m_Dec = Encoding.UTF8.GetDecoder(); m_Dec.GetChars(bytedata, 0, bytedata.Length, m_charData, 0); Console.WriteLine("Read From File Succeed!"); Console.WriteLine(m_charData); } catch (IOException ex) { Console.WriteLine("There is an IOException"); Console.WriteLine(ex.Message); } Console.ReadLine(); } } }