Skip to content

文件管理

获取本地路径

csharp
 //转义符@
  string pathDemo = @"E:\my-study\c#文件管理\本地资源\副本股票交易所技术合同.docx";
  string path = "E:\\my-study\\c#文件管理\\本地资源\\apache.js";

File

方法解释示例
Exists判断文件是否存在File.Exists(path)
Create创建文件File.Create(path);
Delete删除文件File.Delete(path);
WriteAllText写入文件(会替换当前文件)File.WriteAllText(path, "写入文件内容")
AppendAllText追加文件(不会替换当前文件)File.AppendAllText(path, "追加文件内容");
ReadAllText读取文件string content = File.ReadAllText(path);
Copy复制文件File.Copy(path, "E:\\my-study\\c#文件管理\\本地资源\\副本apache.js");

FileInfo

csharp
//使用
FileInfo fileInfo = new FileInfo(path);
属性解释示例
Exists判断文件是否存在fileInfo.Exists
FullName获取文件完整路径fileInfo.FullName
Name获取文件名fileInfo.Name
Length获取文件长度fileInfo.Length
IsReadOnly判断文件是否为只读fileInfo.IsReadOnly
CreationTime获取文件的创建时间fileInfo.CreationTime
LastAccessTime获取文件的最后访问时间fileInfo.LastAccessTime
Extension获取文件扩展名fileInfo.Extension
Directory获取文件所在目录fileInfo.Directory

FileStream

读取文件

csharp
string path = "E:\\my-study\\c#文件管理\\本地资源\\apache.js";

//读取文件,没有文件不创建
FileStream fileStream = new FileStream(path, FileMode.Open); 

//读取文件没有的话就创建
FileStream fileStream = new FileStream(path, FileMode.OpenOrCreate);

获取文件内容

csharp
byte[] buffer = new byte[fileStream.Length]; //创建一个字节数组,长度为文件长度     
fileStream.Read(buffer, 0, buffer.Length); //将文件内容读入字节数组
string content = Encoding.UTF8.GetString(buffer); //将字节数组转换为字符串
Console.WriteLine(content); //输出文件内容
fileStream.Close(); //关闭文件流

写入文件

csharp
string path = "E:\\my-study\\c#文件管理\\本地资源\\apache.js";
string content = "写入文件内容";
FileStream fileStream = new FileStream(path, FileMode.OpenOrCreate);
byte[] buffer = Encoding.UTF8.GetBytes(content); //将字符串转换为字节数组
fileStream.Write(buffer, 0, buffer.Length); //将字节数组写入文件
fileStream.Close(); //关闭文件流

StreamReaderWriter

读取文件

csharp
string path = "E:\\my-study\\c#文件管理\\本地资源\\apache.js";
StreamReader streamReader = new StreamReader(path); //创建一个StreamReader对象,用于读取文件
string content = streamReader.ReadToEnd(); //读取文件内容
Console.WriteLine(content); //输出文件内容
streamReader.Close(); //关闭StreamReader对象

写入文件

csharp
string path = "E:\\my-study\\c#文件管理\\本地资源\\apache.js";
string content = "写入文件内容";
StreamWriter streamWriter = new StreamWriter(path, false); //创建一个StreamWriter对象,用于写入文件 false表示覆盖文件内容,true表示追加文件内容
streamWriter.Write(content); //将内容写入文件
streamWriter.Close(); //关闭StreamWriter对象

DirectoryInfo

csharp
//使用
DirectoryInfo directoryInfo = new DirectoryInfo(path);
属性解释示例
Exists判断目录是否存在directoryInfo.Exists
FullName获取文件完整路径directoryInfo.FullName
Name获取文件名directoryInfo.Name
CreationTime获取文件的创建时间directoryInfo.CreationTime
LastAccessTime获取文件的最后访问时间directoryInfo.LastAccessTime
Extension获取文件扩展名directoryInfo.Extension
Attributes获取文件属性,如只读、隐藏等directoryInfo.Attributes
Parent获取父目录directoryInfo.Parent
Root获取根目录directoryInfo.Root
方法解释示例
Create创建项目directoryInfo.Create()
Delete删除项目directoryInfo.Delete()
GetFiles获取目录下的所有文件directoryInfo.GetFiles()

Released under the MIT License.