C#中的File类

昨天和大家一起学习了C#中处理JSON格式数据插件Newtonsoft.dll的用法,想必在以后的业务中处理JSON格式数据时,都会游刃有余。

今天咱们一起来看下在C#中是如何处理文件的,关于文件的操作都有哪些方法。

在C#中关于文件的操作都在命名空间System.IO下,当使用File类时,VS会自动引用其System.IO,如下面代码一样。.

using System.IO;

那么在此命名空间下都有哪些方法和属性。具体可以看MSDN的介绍,很详细。

https://docs.microsoft.com/zh-cn/dotnet/api/system.io.file?redirectedfrom=MSDN&view=netframework-4.8

File类的常用方法

创建文件

File.Create(@"文件路径");

删除文件

File.Delete(@"文件路径");

复制文件

File.Copy("被复制文件路径","新文件路径");

剪切文件

File.Move("被剪切文件路径","新文件路径");

读取文件,返回字节数组

private string AnalysiyFile(string filePath) 
{
    byte[] buffer = File.ReadAllBytes(filePath); 
    //将字节解码,先确定编码方式,再解码字节数组
    string tempValue = Encoding.GetEncoding("UTF8").GetString(buffer);
    return tempValue;
}

将数据写入文件

private void WriteFile(string message,string filePath) 
{            
      //把字符串用编码转成字节数组
    byte[] buffer = Encoding.GetEncoding("UTF8").GetBytes(message);
    File.WriteAllBytes(filePath, buffer);
}

判断文件是否存在

if (File.Exists(filePath))
{

}

我们来看下MSDN上面介绍的一个例子,很详细,后面如果有哪些类不太懂或者以前没接触过,首先就去看MSDN上的官方文档,介绍的都很详细。


Demo

检查文件是否存在,根据结果创建新文件并对其进行写入,或者打开现有文件并从中读取。

string path = @"d:\test.txt";
if (!File.Exists(path))
{
    // 往文件中写入3行数据
    using (StreamWriter sw = File.CreateText(path))
    {
        sw.WriteLine("Hello");
        sw.WriteLine("And");
        sw.WriteLine("Welcome");
    }
}

// 打开文件并按行读取数据
using (StreamReader sr = File.OpenText(path))
{
    string s;
    while ((s = sr.ReadLine()) != null)
    {
        Console.WriteLine(s);
    }
}

今天File文件类的学习就到这里,很高兴你能看到这里。