名称空间:System.IO
浏览文件系统和执行操作的类:
System.MarshalByRefObject .net中用于远程操作的基对象类,允许在应用程序域之间编组数据
FileSystemInfo 文件系统对象的基类
FileInfo和File 文件系统上的文件
Directory和DirectoryInfo 文件系统上的文件夹
Path 处理路径名
DriveInfo 驱动器的信息
递归访问目录和文件:
string outputText = ""; int level = -1; int indentCount = 0; //文件夹计数 int fileCount = 0; //文件计数 private string showDirAndFile(DirectoryInfo info) { level++; //输出文件夹信息 outputText += "<br />" + level; for (int i = 0; i < level; i++) { outputText += " "; } outputText = outputText + info.Name; //输出文件信息 FileInfo[] files = info.GetFiles(); foreach (FileInfo file in files) { outputText += "<br />" + level; for (int i = 0; i < level; i++) { outputText += " "; } outputText = outputText + file.Name; fileCount++; } foreach (DirectoryInfo inf in info.GetDirectories()) { showDir(inf); indentCount++; } level--; return outputText; }
流:
流是传输数据的对象,数据传输有两个方向:
- 如果数据从外部源传输到程序中,这是读取流
- 如果数据是从程序传输到外部源,这是写入流
复制文件:
int bufferSize = 1024; private void Copy(string inputPath, string outputPath) { Stream inputStream = File.OpenRead(inputPath); Stream outputStream = File.OpenWrite(outputPath); BufferedStream inputBufferedStream = new BufferedStream(inputStream); BufferedStream outputBufferedStream = new BufferedStream(outputStream); byte[] buffer = new byte[bufferSize]; int bytesRead; //从流中读取指定个数的字节到字节数据组中,指针移动位置,返回成功读取的字节数 bytesRead = inputBufferedStream.Read(buffer, 0, bufferSize); while (bytesRead != 0) //bytesRead=0 表示读完了 { //将字节数组中的数据写到流中指定位置 outputBufferedStream.Write(buffer, 0, bufferSize); bytesRead = inputBufferedStream.Read(buffer, 0, bufferSize); } //强制将缓冲区的数据写入文件 outputBufferedStream.Flush(); outputBufferedStream.Close(); inputBufferedStream.Close(); }
异步读文件:
1 byte[] buffer = new byte[1024]; 2 //char[] chars = new char[1024]; 3 //IAsyncResult asresult; 4 FileStream fs; 5 AsyncCallback cb; 6 private void AsyncRead1() 7 { 8 fs = new FileStream("F:\\1988:我想和这个世界谈谈.txt", FileMode.Open); 9 cb = new AsyncCallback(HandleRead); 10 fs.BeginRead(buffer, 0, 1024, cb, null); 11 } 12 13 private void HandleRead(IAsyncResult ar) 14 { 15 int rendBytes = fs.EndRead(ar); 16 if (rendBytes != 0) 17 { 18 //Decoder decoder = Encoding.Default.GetDecoder(); 19 //decoder.GetChars(buffer, 0, 1024, chars, 0); 20 //foreach (char i in chars) 21 //{ 22 // Response.Write(i); 23 //} 24 string text = Encoding.GetEncoding("GB2312").GetString(buffer, 0, 1024); 25 Response.Write(text); 26 fs.BeginRead(buffer, 0, buffer.Length, cb, null); 27 } 28 }