C#:文件操作
- DriveInfo 获取驱动器信息
1 //获取驱动器信息 2 void GetDriveInfo() 3 { 4 DriveInfo driveInfo = new DriveInfo("C"); 5 Console.WriteLine("驱动器的名称:" + driveInfo.Name); 6 Console.WriteLine("驱动器类型:" + driveInfo.DriveType); 7 Console.WriteLine("驱动器可用空间大小:" + driveInfo.TotalFreeSpace / Math.Pow(1024, 3) + "G"); 8 Console.WriteLine("驱动器总大小:" + driveInfo.TotalSize / Math.Pow(1024, 3) + "G"); 9 } 10 //获取所有驱动器 11 void GetDrivesInfos() 12 { 13 DriveInfo[] driveInfos = DriveInfo.GetDrives(); 14 foreach(DriveInfo info in driveInfos) 15 { 16 Console.WriteLine("驱动器名称:" + info.Name); 17 Console.WriteLine("驱动器文件格式:" + info.DriveFormat); 18 } 19 }
- Directory 文件夹操作
1 void CreateDirectory() 2 { 3 //如果存在就删除文件夹,不存在就创建 4 if (Directory.Exists("D:\\code")) 5 { 6 Directory.Delete("D:\\code", true); 7 } 8 else 9 { 10 Directory.CreateDirectory("D:\\code"); 11 } 12 13 //第二种方式创建文件夹 14 DirectoryInfo directoryInfo = new DirectoryInfo("D:\\code"); 15 directoryInfo.Create(); 16 //创建子文件夹 17 directoryInfo.CreateSubdirectory("code-1"); 18 //删除文件夹 19 directoryInfo.Delete(true); 20 }
- File 文件操作
1 void CreateFile() 2 { 3 FileInfo fileInfo = new FileInfo("D:\\code\\test.txt"); 4 //如果文件不存在则创建文件 5 if (!fileInfo.Exists) 6 { 7 fileInfo.Create().Close(); 8 } 9 //移动文件,如果新目录不存在该文件则可以移动,不加该判断会报错 10 FileInfo newfileInfo = new FileInfo("D:\\code\\code-1\\test1.txt"); 11 if (!newfileInfo.Exists) 12 { 13 fileInfo.MoveTo("D:\\code\\code-1\\test1.txt"); 14 } 15 //输出文件信息 16 Console.WriteLine("文件路径:" + fileInfo.Directory); 17 Console.WriteLine("文件名称:" + fileInfo.Name); 18 Console.WriteLine("文件是否只读:" + fileInfo.IsReadOnly); 19 Console.WriteLine("文件大小:" + fileInfo.Length); 20 }
- StreamReader 读取流
1 void Reader() 2 { 3 string path = @"D:\\code\test.txt"; 4 StreamReader streamReader = new StreamReader(path); 5 //一直读取到文件末尾 6 //Peek():获取流中的下一个字符的整数,如果没有获取到字符, 则返回 -1 7 while (streamReader.Peek() != -1) 8 { 9 Console.WriteLine(streamReader.ReadLine()); 10 } 11 //读完之后别忘了关闭文件 12 streamReader.Close(); 13 }
- StreamWrite 写入流
1 void WriteToFile() 2 { 3 string path = @"D:\\code\test.txt"; 4 StreamWriter streamWrite = new StreamWriter(path); 5 //如果已存在该文本,此方法会覆盖 6 streamWrite.WriteLine("写入一行"); 7 //刷新缓存区 8 streamWrite.Flush(); 9 //关闭流 10 streamWrite.Close(); 11 }
- FileStream 文件流
1 //写入 2 string path = @"D:\\code\\test.txt"; 3 FileStream fileStream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); 4 string msg = "just test"; 5 byte[] bytes = Encoding.UTF8.GetBytes(msg); 6 fileStream.Write(bytes, 0, bytes.Length); 7 fileStream.Flush(); 8 fileStream.Close(); 9 //读取 10 string path = @"D:\\code\\test.txt"; 11 FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read); 12 byte[] bytes = new byte[fileStream.Length]; 13 fileStream.Read(bytes, 0, bytes.Length); 14 char[] c = Encoding.UTF8.GetChars(bytes); 15 Console.WriteLine(c); 16 fileStream.Close();