稍微总结下,System.IO提供了四种类型来实现,对单个文件和计算机目录结构的操作。Directory和File通过静态成员实现建立、删除、复制和移动操作(上图没有提及)。而FileInfo和DirectryInfo类型则通过实例级方法来实现类似的功能,并且更加推荐使用,原因是它们的成员方法返回强类型的对象。
FileStream和StreamReader/StreamWriter的主要区别在于,FileStream操作的是字节/字节数组;而StreamReader/StreamWriter可以操作字符串。
class="code">public void CreateByteFile() { var fileInfo = new FileInfo(string.Format(@"{0}\Test.dat", Environment.CurrentDirectory)); using (var fileStream = fileInfo.Open(FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.None)) { const string msg = "Hello"; var msgAsByteArray = Encoding.Default.GetBytes(msg); fileStream.Write(msgAsByteArray,0,msgAsByteArray.Length); fileStream.Position = 0; Console.WriteLine("Your Message as an array of bytes:\n"); var bytesFormFile = new byte[msgAsByteArray.Length]; for (var i = 0; i < msgAsByteArray.Length; i++) { bytesFormFile[i] =(byte) fileStream.ReadByte(); Console.WriteLine(bytesFormFile[i]); } Console.WriteLine("\n Decoded Message: "); Console.WriteLine(Encoding.Default.GetString(bytesFormFile)); } }
public void WriteCharFile() { var fileInfo = new FileInfo(string.Format( "{0}reminders.txt", AppDomain.CurrentDomain.BaseDirectory)); using (var streamWriter = fileInfo.CreateText()) { streamWriter.WriteLine("Don't forget Mother's Day this year..."); streamWriter.WriteLine("Don't forget Father's Day this year..."); streamWriter.WriteLine("Don't forget These numbers:"); for (var i = 0; i < 10; i++) { streamWriter.Write(i + " "); } streamWriter.Write(streamWriter.NewLine); } Console.WriteLine("Created file and wrote some thoughts..."); Console.ReadKey(); }