C# File class: file operations

The File class is a static class, and the provided class members are also static. You can call its class members directly with the name of the File class.

The common methods for obtaining or setting file information in the File class are shown in the figure below.
Insert picture description here
example:

using System;
using System.IO;

namespace MySpcae
{
    
    
    class Program
    {
    
    

        static void Main(string[] args)
        {
    
    
            //在E盘下创建test01和test02文件
            //@跟着的字符\就不表示转移字符了
            //下面两行的写法都是一样的意思
            Directory.CreateDirectory("E:\\test01");
            Directory.CreateDirectory(@"E:\test02");
            string path = @"E:\test01\test01.txt";

            //创建文件
            FileStream fs = File.Create(path);


            Console.WriteLine("文件创建时间: " + File.GetCreationTime(path));
            Console.WriteLine("文件最后被写入的时间: " + File.GetLastWriteTime(path));
            //关闭文件流
            fs.Close();

            string newPath = @"E:\test02\test01.txt";
            
            //判断改路径下的文件是否存在,存在就删除
            if(File.Exists(newPath))
            {
    
    
                File.Delete(newPath);
            }
            //将指定的文件移动到新位置
            //第一个参数源文件地址
            //第二个参数目标文件地址
            File.Move(path, newPath);
        }
    }

}

Operational results:
Insert picture description here
In actual applications, it is more commonly used to complete file operations using the Fileinfo class compared with the File class

Guess you like

Origin blog.csdn.net/weixin_50188452/article/details/115023300