C# 文件操作

2019-10-29  本文已影响0人  李霖弢

System.IO命名空间中,有以下类支持文件/路径操作

DriveInfo 驱动器信息

DriveInfo di = new DriveInfo(@"C:\");
静态方法
DriveInfo[] allDrives = DriveInfo.GetDrives();
实例属性

DirectoryInfo 目录信息

实例方法

FileInfo 文件信息

FileInfo fi = new FileInfo(@"C:\Users\62406\sampleQuotes.txt");

Directory 静态方法检索目录信息

目录没有直接的复制方法,只能通过新建目录并遍历复制所有文件的方式

静态方法
string currentDirUrl = Directory.GetCurrentDirectory();
//C:\Users\62406\Desktop\StudyC\ConsoleApp4\bin\Debug\netcoreapp2.1
string[] files = Directory.GetFiles(currentDirUrl , "*.txt");

File 静态方法检索文件信息

静态方法

Path 路径操作

静态方法

FileStream 文件流

实例方法
using (FileStream fs = System.IO.File.Create(filePath))
{
    string msg = "hello";
    byte[] myByte = System.Text.Encoding.UTF8.GetBytes(msg);
    foreach (var item in myByte)
    {
        fs.WriteByte(item);
    }
}
byte[] readBuffer = System.IO.File.ReadAllBytes(filePath);
string content = System.Text.Encoding.UTF8.GetString(readBuffer);
Console.WriteLine(content);//hello

StreamWriter

不同于FileStream输入byteStreamWriter会直接输入文本内容。
实例化时,第二个参数若为true,则保留原文件,否则直接新建一个覆盖。默认为false。

实例方法
using (System.IO.StreamWriter file = 
  new System.IO.StreamWriter(string sourceUrl, bool keepOriginal))
  {
    file.WriteLine(string textContent);
  }

StreamReader

读取后需要主动调用Close方法。

int counter = 0;  
string line;  
  
// Read the file and display it line by line.  
System.IO.StreamReader file =   
    new System.IO.StreamReader(@"c:\test.txt");  
while((line = file.ReadLine()) != null)  
{  
    System.Console.WriteLine(line);  
    counter++;  
}  
  
file.Close();  
System.Console.WriteLine("There were {0} lines.", counter);  
// Suspend the screen.  
System.Console.ReadLine();  

System.Diagnostics.Process

用于打开某个链接网址(弹窗)、文件目录,或系统特殊文件夹(控制面板等)

静态方法
实例方法
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = "iexplore.exe";   //IE浏览器,可以更换
process.StartInfo.Arguments = "http://www.baidu.com";
process.Start();
System.Diagnostics.ProcessStartInfo processStartInfo = new System.Diagnostics.ProcessStartInfo();
processStartInfo.FileName = "explorer.exe";  //资源管理器
processStartInfo.Arguments = @"D:\";
System.Diagnostics.Process.Start(processStartInfo);
上一篇 下一篇

猜你喜欢

热点阅读