C# 常用的文件IO操作

目录

 

一、IO流

1.文件夹操作 Directory类

2.文件操作 File类

3.路径操作 Path类

4.读取文件 StreamReader类

5.写入文件 StreamWriter类

二、动态链接库kernel32

1.写入文件

2.读取文件


一、IO流

注意:
路径有3种方式,当前目录下的相对路径、当前工作盘的相对路径、绝对路径。以C:\Temp\Directory为例(假定当前工作目录为C:\Temp)。“Directory”,“\Temp\Directory”,“C:\Temp\Directory”都表示C:\Temp\Directory。
另外,在C#中 “\”是特殊字符,要表示它的话需要使用“\\”。由于这种写法不方便,C#语言提供了@对其简化。只要在字符串前加上@即可直接使用“\”。所以上面的路径在C#中应该表示为“Directory”,@“\Temp\Directory”,@“C:\Temp\Directory”。

1.文件夹操作 Directory类

1.判断文件夹是否存在

Directory.Exists(filePath);//判断文件夹是否存在

2.获取目录下指定类型的文件

Directory.GetFiles(filePath, "*.ttf.meta", SearchOption.TopDirectoryOnly);//获取指定格式的文件

通配符说明:

* :匹配在该位置的零个或多个字符

? :匹配在该位置的零个或一个字符

通配符以外的字符为原义字符。 例如,searchPattern 字符串 "*t" 搜索 path 以字母 "t" 结尾的所有名称。 searchPattern 字符串 "s*" 搜索 path 以字母 "s" 开头的所有名称。

详情见  https://msdn.microsoft.com/zh-cn/library/ms143316(v=vs.110).aspx

3.获取当前工程目录

Environment.CurrentDirectory

4.删除指定目录

Directory.Delete("D:\\code", true);

5.创建指定目录

Directory.CreateDirectory("D:\\code");

6.查看当前路径

Directory.GetCurrentDirectory()

7.设置目录属性

DirectoryInfo NewDirInfo = new DirectoryInfo(@"c:\temp\NewDirectoty");
//设置目录属性未只读、隐藏
NewDirInfo.Atttributes = FileAttributes.ReadOnly|FileAttributes.Hidden;

8.移动目录

Directory.Move(@"c:\temp\NewDirectory",@"c:\temp\Move");

9.获取指定目录下的所有子目录

string [] directorys = Directory.GetDirectories (@"c:\temp");

2.文件操作 File类

1.判断文件是否存在

File.Exists(string filePath)

2.创建文件

public void CreateFile( string filePath )
{
    if (File.Exists(filePath)) return;//判断文件是否存在
    FileStream fileStream = File.Create(filePath);
    if (fileStream != null)
    fileStream.Close();//关闭文件流
}

3.删除文件

File.Delete(string filePath);

4.移动文件

File.Move(string path, string newPath);

5.文件创建时间

File.GetCreationTime(string path);//获取
File.SetCreationTime(string path, DateTime creationTime);//设置

6.文件最后被写入时间

File.GetLastWriteTime(string path);//获取
SetLastWriteTime(string path, DateTime lastWriteTime);//设置

7.文件上次被访问的时间

File.GetLastAccessTime(string path);//获取
File.SetLastAccessTime(string path, DateTime lastWriteTime);//设置

8.打开文件

private void OpenFile()
{
 FileStream textFile=File.Open(@"c:\temp\newFile.txt",FileMode.Append);
 byte [] Info = {(byte)'h',(byte)'e',(byte)'l',(byte)'l',(byte)'o'};
 textFile.Write(Info,0,Info.Length);
 textFile.Close();
}

9.复制文件

File.Copy(@"c:\temp\newFile.txt",@"c:\temp\Copy.txt",true);

10.设置文件属性

//将c:\temp\newFile.txt文件设置为只读、隐藏
File.SetAttributes(@"c:\temp\newFile.txt",FileAttributes.ReadOnly|FileAttributes.Hidden);

11.读取整个文件

string allStr = File.ReadAllText(filePath);

3.路径操作 Path类

Path类是静态类,直接用类名调用以下方法即可

string ChangeExtension(string path, string extension)更改路径字符串的扩展名
string Combine(params string[] paths)将字符串数组组合成一个路径
string Combine(string path1, string path2)将两个字符串组合成一个路径
string GetDirectoryName(string path)返回指定路径字符串的目录信息
string GetExtension(string path)返回指定路径字符串的扩展名
string GetFileName(string path)返回指定路径字符串的文件名和扩展名
string GetFileNameWithoutExtension(string path)返回不具有扩展名的指定路径字符串的文件名
string GetFullPath(string path)返回指定路径字符串的绝对路径
char[] GetInvalidFileNameChars()获取包含不允许在文件名中使用的字符的数组
char[] GetInvalidPathChars()获取包含不允许在路径名中使用的字符的数组
string GetPathRoot(string path)获取指定路径的根目录信息
string GetRandomFileName()返回随机文件夹名或文件名
string GetTempPath()返回当前用户的临时文件夹的路径
bool HasExtension(string path)返回路径是否包含文件的扩展名
bool IsPathRooted(string path)返回路径字符串是否包含根

4.读取文件 StreamReader类

1.StreamReader类的构造方法

构造方法说明
StreamReader(Stream stream)为指定的流创建 StreamReader 类的实例
StreamReader(string path)为指定路径的文件创建 StreamReader 类的实例
StreamReader(Stream stream, Encoding encoding) 用指定的字符编码为指定的流初始化 StreamReader 类的一个新实例
StreamReader(string path, Encoding encoding)用指定的字符编码为指定的文件名初始化  StreamReader 类的一个新实例

2.StreamReader类的属性和方法

属性或方法作用
Encoding CurrentEncoding只读属性,获取当前流中使用的编码方式
bool EndOfStream只读属性,获取当前的流位置是否在流结尾
void Close()关闭流
int Peek()获取流中的下一个字符的整数,如果没有获取到字符, 则返回 -1
int Read()获取流中的下一个字符的整数
int Read(char[] buffer, int index, int count)从指定的索引位置开始将来自当前流的指定的最多字符读到缓冲区
string ReadLine()从当前流中读取一行字符并将数据作为字符串返回
string ReadToEnd()读取来自流的当前位置到结尾的所有字符

3.代码示例

//定义文件路径
string path = @"C:\temp\test.txt";
//创建 StreamReader 类的实例
StreamReader streamReader = new StreamReader(path);
//判断文件中是否有字符
while (streamReader.Peek() != -1)
{
    //读取文件中的一行字符
    string str = streamReader.ReadLine();
    Console.WriteLine(str);
}
streamReader.Close();

5.写入文件 StreamWriter类

1.StreamWriter类的构造方法

构造方法说明
StreamWriter(Stream stream) 为指定的流创建 StreamWriter 类的实例
StreamWriter(string path)为指定路径的文件创建 StreamWriter 类的实例
StreamWriter(Stream stream, Encoding encoding)用指定的字符编码为指定的流初始化 StreamWriter 类的一个新实例
StreamWriter(string path, Encoding encoding)用指定的字符编码为指定的文件名初始化 StreamWriter 类的一个新实例

2.StreamWriter类的属性和方法

属性或方法作用
bool AutoFlush属性,获取或设置是否自动刷新缓冲区
Encoding Encoding只读属性,获取当前流中的编码方式
void Close()关闭流
void Flush()刷新缓冲区
void Write(char value)将字符写入流中
void WriteLine(char value)将字符换行写入流中
Task WriteAsync(char value)将字符异步写入流中
Task WriteLineAsync(char value) 将字符异步换行写入流中

3.代码示例

string path = @"C:\temp\test.txt";
//创建StreamWriter 类的实例
StreamWriter streamWriter = new StreamWriter(path);
//向文件中写入姓名
streamWriter.WriteLine("小张");
//向文件中写入手机号
streamWriter.WriteLine("13112345678");
//刷新缓存
streamWriter.Flush();
//关闭流
streamWriter.Close();

二、动态链接库kernel32

kernel32.dll是Windows9x/Me中非常重要的32位动态链接库文件,属于内核级文件。它控制着系统的内存管理、数据的输入输出操作和中断处理,当Windows启动时,kernel32.dll就驻留在内存中特定的写保护区域,使别的程序无法占用这个内存区域。

1.写入文件

/// <summary>
/// 写入文件
/// </summary>
/// <param name="strSection">要写入的段落名</param>
/// <param name="strKey">要写入的键</param>
/// <param name="strValue">要写入的值</param>
/// <param name="strFilePath">INI文件的完整路径和文件名</param>
/// <returns></returns>
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string strSection, string strKey, string strValue, string strFilePath);

/// <summary>
/// 写入字符串
/// </summary>
public void WriteString(string strSection,string strKey,string strValue)
{
    WritePrivateProfileString(strSection, strKey, strValue, m_filePath);
}
/// <summary>
/// 写整形
/// </summary>
public void WriteInt(string strSection, string strKey, int intValue)
{
    WriteString(strSection, strKey, intValue.ToString());
}
/// <summary>
/// 写整形
/// </summary>
public void WriteInt(string strSection, string strKey, long intValue)
{
    WriteString(strSection, strKey, intValue.ToString());
}
/// <summary>
/// 写bool
/// </summary>
public void WriteBool(string strSection, string strKey, bool value)
{
    string str = value ? "true" : "false";
    WriteString(strSection, strKey, str);
}

2.读取文件

/// <summary>
/// 读取文件
/// </summary>
/// <param name="strSection">要读取的段落名</param>
/// <param name="strKey">要读取的键</param>
/// <param name="strDefine">读取异常的情况下的默认值</param>
/// <param name="retValue">key所对应的值,如果该key不存在则返回空值</param>
/// <param name="nSize">值允许的大小</param>
/// <param name="strFilePath">INI文件的完整路径和文件名</param>
/// <returns></returns>
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string strSection, string strKey, string strDefine, StringBuilder retValue, int nSize, string strFilePath);

/// <summary>
/// 读取字符串
/// </summary>
public string ReadString(string strSection, string strKey, string strDefine = "" )
{
    StringBuilder retValue = new StringBuilder(1024);
    int nSize = GetPrivateProfileString(strSection, strKey, strDefine, retValue, 1024, m_filePath);
    return retValue.ToString();
}
/// <summary>
/// 读取int
/// </summary>
public int ReadInt(string strSection, string strKey, int intDefine = 0)
{
    string str = ReadString(strSection, strKey, intDefine.ToString());
    int nValue = 0;
    int.TryParse(str, out nValue);
    return nValue;
}
/// <summary>
/// 读取bool
/// </summary>
public bool ReadBool(string strSection, string strKey, bool value = false)
{
    string strv = value ? "true" : "false";
    string str = ReadString(strSection, strKey, strv );
    return str.Equals("true");
}

 

  • 4
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值