1、C# IO流应用详细示例 目录 1 目 录 创建目录清单2 从文件读取文本3 从文件写入文本1.4 从文件写入文本2.5 从字符串中读取字符6 打开并追加到日志文件.7 对新建的数据文件进行读取和写入.8 构成流应用1.9 构成流应用2.10 通用流类BufferedStream应用.11 通用流类CryptoStream应用14 通用流类MemoryStream应用17 文件操作类Directory应用119 文件操作类Directory应用220 向字符串写入字符21 用于从流读取和写入流的类BinaryReader应用.22 用于从流读取和写入流的类BinaryWriter应用25 用于
2、从流读取和写入流的类StreamReader应用28 用于从流读取和写入流的类StringReader应用29 用于从流读取和写入流的类StringWriter应用.31 用于从流读取和写入流的类TextReader应用33 用于从流读取和写入流的类TextWriter应用.34 用于文件的类DirectoryInfo应用.35 用于文件的类DriveInfo应用.36 用于文件的类FileInfo应用37 用于文件的类FileStream应用139 用于文件的类FileStream应用240 用于文件的类File应用41 用于文件的类Path应用.43 C# IO流应用详细示例 整理By小墨
3、 2 创建目录清单 using System; using System.IO; class Test public static void Main(String args) string path = “.“; if (args.Length 0) if (File.Exists(args0) /如果有输入,则选取输入的 path = args0; else /赋值当前目录 Console.WriteLine(“0 not found; using current directory:“, args0); DirectoryInfo dir = new DirectoryInfo(path
4、); foreach (FileInfo f in dir.GetFiles(“*.exe“) String name = f.Name; long size = f.Length; DateTime creationTime = f.CreationTime; Console.WriteLine(“程序名为:0 大小为:1,-12:N0字节生成时间:2,-20:g “, name, size, creationTime); C# IO流应用详细示例 整理By小墨 3 从文件读取文本 using System; using System.IO; class Test public static
5、 void Main() try using (StreamReader sr = new StreamReader(“c:tempTestFile.txt“) String line; /读取数据显示信息 Console.WriteLine(“文件信息为:n“); while (line = sr.ReadLine() != null) Console.WriteLine(line); catch (Exception e) Console.WriteLine(“文件没有被读,错误信息为:“); Console.WriteLine(e.Message); C# IO流应用详细示例 整理By小
6、墨 4 从文件写入文本1 using System; using System.IO; class Test public static void Main() using (StreamWriter sw = new StreamWriter(“c:tempTestFile.txt“) /加入一些信息到文件中 sw.Write(“This is the “); sw.WriteLine(“header for the file.“); sw.WriteLine(“-“); sw.Write(“The date is: “); sw.WriteLine(DateTime.Now); Conso
7、le.WriteLine(“已经将数据写入文件中!“); C# IO流应用详细示例 整理By小墨 5 从文件写入文本2 using System; using System.IO; public class TextToFile private const string FILE_NAME = “c:temptest.txt“; public static void Main(String args) if (File.Exists(FILE_NAME) Console.WriteLine(“0 already exists.“, FILE_NAME); return; using (Stre
8、amWriter sw = File.CreateText(FILE_NAME) sw.WriteLine(“This is a test.“); sw.WriteLine(“我能写这些信息“); sw.Close(); Console.WriteLine(“文件已完成,请查看0“, FILE_NAME); C# IO流应用详细示例 整理By小墨 6 从字符串中读取字符 using System; using System.IO; public class CharsFromStr public static void Main(String args) / 声明一个字符串 String st
9、r = “abcdefghijklmnopqrstuvwxyz“; /声明一个数组 char b = new char24; StringReader sr = new StringReader(str); / 从StringReader读取信息 sr.Read(b, 0, 10); / 显示信息 Console.WriteLine(b); sr.Close(); C# IO流应用详细示例 整理By小墨 7 打开并追加到日志文件 using System; using System.IO; class Logfile public static void Main(String args) u
10、sing (StreamWriter w = File.AppendText(“c:templog.txt“) Log(“Test1“, w); Log(“Test2“, w); / 关闭文件 w.Close(); /打开文件e. using (StreamReader r = File.OpenText(“c:templog.txt“) Logmsg(r); public static void Log(String logMessage, TextWriter w) w.Write(“rn开始记录日志信息y : “); w.WriteLine(“0 1“, DateTime.Now.ToL
11、ongTimeString(), DateTime.Now.ToLongDateString(); w.WriteLine(“ :0“, logMessage); w.WriteLine(“-“); w.Flush(); public static void Logmsg(StreamReader r) String line; while (line = r.ReadLine() != null) Console.WriteLine(line); r.Close(); C# IO流应用详细示例 整理By小墨 8 对新建的数据文件进行读取和写入 using System; using Syst
12、em.IO; class MyStream private const string FILE_NAME = “c:tempTest.data“; public static void Main(String args) / 生成文件 if (File.Exists(FILE_NAME) Console.WriteLine(“0 already exists!“, FILE_NAME); return; FileStream fs = new FileStream(FILE_NAME, FileMode.CreateNew); BinaryWriter w = new BinaryWriter
13、(fs); / 写入数据 for (int i = 0; i -1) String input = sr.ReadLine(); Console.WriteLine(input); sr.Close(); C# IO流应用详细示例 整理By小墨 10 构成流应用2 using System; using System.IO; public class Test private const string FILE_NAME = “c:tempMyFile.txt“; public static void Main(String args) if (!File.Exists(FILE_NAME)
14、Console.WriteLine(“0文件不存在.“, FILE_NAME); return; FileStream f = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read, FileShare.Read); BinaryReader sr = new BinaryReader(f); Console.WriteLine(“文件内容为:“); while (sr.PeekChar() -1) byte input = sr.ReadByte(); Console.WriteLine(input); sr.Close(); C#
15、 IO流应用详细示例 整理By小墨 11 通用流类BufferedStream应用 using System; using System.IO; using System.Globalization; using System.Net; using System.Net.Sockets; public class Client_service const int dataArraySize = 100; const int streamBufferSize = 1000; const int numberOfLoops = 10000; static void Main(string args
16、) string remoteName = “192.168.1.110“; / 建立socket Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); / 建立连接 clientSocket.Connect(new IPEndPoint( Dns.Resolve(remoteName).AddressList0, 1800); Console.WriteLine(“Client is connected.n“); using (Stream netS
17、tream = new NetworkStream(clientSocket, true), bufStream = new BufferedStream(netStream, streamBufferSize) /检查. Console.WriteLine(“NetworkStream 0 seeking.n“, bufStream.CanSeek ? “supports“ : “does not support“); / 发送接收数据 if (bufStream.CanWrite) SendData(netStream, bufStream); if (bufStream.CanRead)
18、 ReceiveData(netStream, bufStream); Console.WriteLine(“n连接关闭“); bufStream.Close(); C# IO流应用详细示例 整理By小墨 12 static void SendData(Stream netStream, Stream bufStream) DateTime startTime; double networkTime, bufferedTime; / 发送随机的数据给服务. byte dataToSend = new bytedataArraySize; new Random().NextBytes(dataT
19、oSend); /使用NetworkStream 发送数据. Console.WriteLine(“start Send data using NetworkStream.“); startTime = DateTime.Now; for (int i = 0; i numberOfLoops; i+) netStream.Write(dataToSend, 0, dataToSend.Length); networkTime = (DateTime.Now - startTime).TotalSeconds; Console.WriteLine(“0 bytes sent in 1 seco
20、nds.n“, numberOfLoops * dataToSend.Length, networkTime.ToString(“F1“); / 使用bufferstream发送数据. Console.WriteLine(“start Send data using BufferedStream.“); startTime = DateTime.Now; for (int i = 0; i numberOfLoops; i+) bufStream.Write(dataToSend, 0, dataToSend.Length); bufStream.Flush(); bufferedTime =
21、 (DateTime.Now - startTime).TotalSeconds; Console.WriteLine(“0 bytes sent in 1 seconds.n“, numberOfLoops * dataToSend.Length, bufferedTime.ToString(“F1“); / 打印出相关信息 Console.WriteLine(“Sending data using the buffered “ + “network stream was 0 1 than using the network “ + “stream alone.n“, (networkTim
22、e / bufferedTime).ToString(“P0“), bufferedTime networkTime ? “faster“ : “slower“); static void ReceiveData(Stream netStream, Stream bufStream) DateTime startTime; double networkTime, bufferedTime = 0; int bytesReceived = 0; byte receivedData = new bytedataArraySize; C# IO流应用详细示例 整理By小墨 13 / 使用Networ
23、kStream.接收信息 Console.WriteLine(“Receiving data using NetworkStream.“); startTime = DateTime.Now; while (bytesReceived numberOfLoops * receivedData.Length) bytesReceived += netStream.Read( receivedData, 0, receivedData.Length); networkTime = (DateTime.Now - startTime).TotalSeconds; Console.WriteLine(
24、“0 bytes received in 1 seconds.n“, bytesReceived.ToString(), networkTime.ToString(“F1“); / 使用BufferedStream.接收信息 Console.WriteLine(“Receiving data using BufferedStream.“); bytesReceived = 0; startTime = DateTime.Now; while (bytesReceived numberOfLoops * receivedData.Length) bytesReceived += bufStrea
25、m.Read( receivedData, 0, receivedData.Length); bufferedTime = (DateTime.Now - startTime).TotalSeconds; Console.WriteLine(“0 bytes received in 1 seconds.n“, bytesReceived.ToString(), bufferedTime.ToString(“F1“); / Print the ratio of read times. Console.WriteLine(“Receiving data using the buffered net
26、work“ + “ stream was 0 1 than using the network stream alone.“, (networkTime / bufferedTime).ToString(“P0“), bufferedTime networkTime ? “faster“ : “slower“); C# IO流应用详细示例 整理By小墨 14 通用流类CryptoStream应用 using System; using System.Security.Cryptography; using System.Text; using System.IO; class test sta
27、tic void Main() try / 建立新的Rijndael对象去生成key Rijndael RijndaelAlg = Rijndael.Create(); / 生成一个字符串去加密. string sData = “I love you.“; string FileName = “c:tempCText.txt“; /加密文件 Console.WriteLine(“开始加密.“); EncryptTextToFile(sData, FileName, RijndaelAlg.Key, RijndaelAlg.IV); Console.WriteLine(“加密成功,并写入文件中,
28、请查看0!“, FileName); / 解密文件 string Final = DecryptTextFromFile(FileName, RijndaelAlg.Key, RijndaelAlg.IV); Console.WriteLine(“n解密成功,内容为:!“); / 显示信息 Console.WriteLine(Final); catch (Exception e) Console.WriteLine(e.Message); Console.ReadLine(); public static void EncryptTextToFile(String Data, String F
29、ileName, byte Key, byte IV) try / 打开文件 FileStream fStream = File.Open(FileName, FileMode.OpenOrCreate); / 生成新的Rijndael对象 Rijndael RijndaelAlg = Rijndael.Create(); C# IO流应用详细示例 整理By小墨 15 / 生成一个加密流使用FileStream CryptoStream cStream = new CryptoStream(fStream, RijndaelAlg.CreateEncryptor(Key, IV), Crypt
30、oStreamMode.Write); / 生成一个streamwriter 使用CryptoStream StreamWriter sWriter = new StreamWriter(cStream); try / 写数据到stream /并加密 sWriter.WriteLine(Data); catch (Exception e) Console.WriteLine(“错误发生: 0“, e.Message); finally / 关闭 sWriter.Close(); cStream.Close(); fStream.Close(); catch (CryptographicExce
31、ption e) Console.WriteLine(“错误发生: 0“, e.Message); catch (UnauthorizedAccessException e) Console.WriteLine(“一个文件错误: 0“, e.Message); public static string DecryptTextFromFile(String FileName, byte Key, byte IV) try / 打开文件. FileStream fStream = File.Open(FileName, FileMode.OpenOrCreate); / 生成新的Rijndael对
32、象 Rijndael RijndaelAlg = Rijndael.Create(); / 生成一个加密流使用FileStream CryptoStream cStream = new CryptoStream(fStream, C# IO流应用详细示例 整理By小墨 16 RijndaelAlg.CreateDecryptor(Key, IV), CryptoStreamMode.Read); / 生成一个加密流使用CryptoStream. StreamReader sReader = new StreamReader(cStream); string val = null; try /读
33、数据并加密 val = sReader.ReadLine(); catch (Exception e) Console.WriteLine(“错误发生: 0“, e.Message); finally / 关闭 sReader.Close(); cStream.Close(); fStream.Close(); / 返回信息串. return val; catch (CryptographicException e) Console.WriteLine(“加密错误发生: 0“, e.Message); return null; catch (UnauthorizedAccessExceptio
34、n e) Console.WriteLine(“文件错误: 0“, e.Message); return null; C# IO流应用详细示例 整理By小墨 17 通用流类MemoryStream应用 using System; using System.IO; using System.Text; class MemStream static void Main() int count; byte byteArray; char charArray; UnicodeEncoding uniEncoding = new UnicodeEncoding(); / 生成数据写入stream byt
35、e firstString = uniEncoding.GetBytes( “When the cats away, the mice will play“); byte secondString = uniEncoding.GetBytes( Path.InvalidPathChars); using (MemoryStream memStream = new MemoryStream(100) /写第一个字符串到stream memStream.Write(firstString, 0, firstString.Length); / 写第二个字符串到stream count = 0; wh
36、ile (count secondString.Length) memStream.WriteByte(secondStringcount+); / 显示stream的属性内容. Console.WriteLine( “Capacity = 0, Length = 1, Position = 2n“, memStream.Capacity.ToString(), memStream.Length.ToString(), memStream.Position.ToString(); / 定位stream的开始位置 memStream.Seek(0, SeekOrigin.Begin); / 从s
37、trem读开始个字符 byteArray = new bytememStream.Length; count = memStream.Read(byteArray, 0, 10); / 读其余的字符 while (count memStream.Length) byteArraycount+ = C# IO流应用详细示例 整理By小墨 18 Convert.ToByte(memStream.ReadByte(); charArray = new charuniEncoding.GetCharCount( byteArray, 0, count); uniEncoding.GetDecoder(
38、).GetChars( byteArray, 0, count, charArray, 0); Console.WriteLine(charArray); C# IO流应用详细示例 整理By小墨 19 文件操作类Directory应用1 using System; using System.IO; class Test public static void Main() / 定义两个目录 string path = “c:MyDir“; string target = “c:TestDir“; try / 判断目录是否存在 if (!Directory.Exists(path) / 如果目录不
39、存在,就生成一个. Directory.CreateDirectory(path); /判断目标目录是否存在 if (Directory.Exists(target) Directory.Delete(target, true); / 移动目录. Directory.Move(path, target); / 生成一个文件在目录中 File.CreateText(target + “filetest1.txt“); File.CreateText(target + “filetest2.txt“); / 判断目录中文件的数目 Console.WriteLine(“在0目录中,文件的个数is 1
40、“, target, Directory.GetFiles(target).Length); catch (Exception e) Console.WriteLine(“The process failed: 0“, e.ToString(); finally C# IO流应用详细示例 整理By小墨 20 文件操作类Directory应用2 using System; using System.IO; public class test public static long DirSize(DirectoryInfo d) long Size = 0; /判断文件的大小. FileInfo
41、fis = d.GetFiles(); foreach (FileInfo fi in fis) Size += fi.Length; return (Size); public static void Main(string args) string direct = “c:temp“; DirectoryInfo d = new DirectoryInfo(direct); Console.WriteLine(“目录大小为 is 0 bytes.“, DirSize(d); C# IO流应用详细示例 整理By小墨 21 向字符串写入字符 using System; using System
42、.IO; using System.Text; public class Charstest public static void Main(String args) / 初始化一个StringBuilder StringBuilder sb = new StringBuilder(“1234567890“); char b = , t, o, , w, r, i, t, e, , t, o, . ; / 生成一个StringWriter StringWriter sw = new StringWriter(sb); / 写个字符到StringBuilderWriter sw.Write(b,
43、 0, 9); / Console.WriteLine(“显示信息为: 0“, sb); / 关闭 sw.Close(); C# IO流应用详细示例 整理By小墨 22 用于从流读取和写入流的类BinaryReader应用 using System; using System.IO; using System.Security.Permissions; class Test static void Main() UpdateSettings appSettings = new UpdateSettings(); Console.WriteLine(“App settings.nAspect R
44、atio: 0, “ + “Lookup directory: 1,nAuto save time: 2 minutes, “ + “Show status bar: 3n“, new Object4appSettings.AspectRatio.ToString(), appSettings.LookupDir, appSettings.AutoSaveTime.ToString(), appSettings.ShowStatusBar.ToString(); / 更改设置. appSettings.AspectRatio = 1.250F; appSettings.LookupDir =
45、“C:Temp“; appSettings.AutoSaveTime = 10; appSettings.ShowStatusBar = true; / 保存新设置. appSettings.Close(); / Store and retrieve application settings. class UpdateSettings const string fileName = “AppSettings#.dat“; float aspectRatio; string lookupDir; int autoSaveTime; bool showStatusBar; public float
46、 AspectRatio get return aspectRatio; set aspectRatio = value; public string LookupDir get return lookupDir; set lookupDir = value; C# IO流应用详细示例 整理By小墨 23 public int AutoSaveTime get return autoSaveTime; set autoSaveTime = value; public bool ShowStatusBar get return showStatusBar; set showStatusBar =
47、 value; public UpdateSettings() / 生成一个初始化的设置. aspectRatio = 1.3333F; lookupDir = “C:AppDirectory“; autoSaveTime = 30; showStatusBar = false; if (File.Exists(fileName) BinaryReader binReader = new BinaryReader(File.Open(fileName, FileMode.Open); try / 如果文件不是空的,读取设置信息. if (binReader.PeekChar() != -1) aspectRatio = binReader.ReadSingle(); lookupDir = binReader.ReadString(); autoSaveTime = binR