C#常用IO操作

文件夹

创建文件夹

//如果文件夹路径不存在则创建文件夹
if (!Directory.Exists(path))
    Directory.CreateDirectory(path);

递归创建文件夹

public void createdir(string fullpath)
        {
            if (!File.Exists(fullpath))
            {
                string dirpath = fullpath.Substring(0, fullpath.LastIndexOf('\\'));
                //string[] pathes = dirpath.Split('\\');
                string[] pathes = fullpath.Split('\\');
                if (pathes.Length > 1)
                {
                    string path = pathes[0];
                    for (int i = 1; i < pathes.Length; i++)
                    {
                        path += "\\" + pathes[i];
                        //如果文件夹路径不存在则创建文件夹
                        if (!Directory.Exists(path))
                            Directory.CreateDirectory(path);
                    }
                }
            }
        }

删除整个文件夹

Directory.Delete(path, true)

获取当前目录的上级目录

DirectoryInfo directory = Directory.GetParent(path);

处理文件/文件夹特殊字符

System.Text.RegularExpressions.Regex.Replace(name, "[\\/:*?\"<>|]", "");

获取目录下的文件(夹)

var list = new string[] { };
string path = @"F:\Download";
//获取路径下所有文件
list = Directory.GetFiles(path);
//获取路径下所有文件夹
list = Directory.GetDirectories(path);
//获取路径下所有文件+文件夹
list = Directory.GetFileSystemEntries(path);
//获取路径下所有Log文件(包含子集文件)
list = Directory.GetFiles(path, "*.log", SearchOption.AllDirectories);
//获取路径下所有Log和Txt文件(包含子集文件)
list = new[] { "*.log", "*.txt" }.SelectMany(f => Directory.GetFiles(path, f, SearchOption.AllDirectories)).ToArray();
//获取路径下所有文件夹(包含子集文件夹)
list = Directory.GetDirectories(path, "*.*", SearchOption.AllDirectories);
//获取路径下所有文件(包含子集文件)
list = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
//获取路径下所有文件+文件夹(包含子集文件+子集文件夹)
list = Directory.GetFileSystemEntries(path, "*.*", SearchOption.AllDirectories);

文件夹拷贝

private static void DirectoryCopy(string sourceDirName, string destDirName)
        {
            DirectoryInfo dir = new DirectoryInfo(sourceDirName);
            DirectoryInfo[] dirs = dir.GetDirectories();

            if (!Directory.Exists(destDirName))
                Directory.CreateDirectory(destDirName);
                
            foreach (FileInfo file in dir.GetFiles())
                file.CopyTo(Path.Combine(destDirName, file.Name), true);

            foreach (DirectoryInfo subdir in dirs)
                DirectoryCopy(subdir.FullName, Path.Combine(destDirName, subdir.Name));

        }

或者使用Neget安装 Microsoft.VisualBasic

string sourcePath = @"D:\test";
string targetPath = @"D:\test_new";
//true:目录中具有相同的文件则覆盖
Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(sourcePath, targetPath,true);

文件

获取文件信息

string filePath = "C:\\Users\\username\\Documents\\example.txt";
FileInfo fileInfo = new FileInfo(filePath);

Console.WriteLine("文件名称:" + fileInfo.Name);
Console.WriteLine("文件全路径:" + fileInfo.FullName);
Console.WriteLine("文件大小(字节):" + fileInfo.Length);
Console.WriteLine("文件创建时间:" + fileInfo.CreationTime);
Console.WriteLine("文件最后修改时间:" + fileInfo.LastWriteTime);

获取文件全路径、目录、扩展名、文件名称

class Program
    {
        static void Main(string[] args)
        {

            //获取当前运行程序的目录
            string fileDir = Environment.CurrentDirectory;
            Console.WriteLine("当前程序目录:"+fileDir);

            //一个文件目录
            string filePath = "C:\\JiYF\\BenXH\\BenXHCMS.xml";
            Console.WriteLine("该文件的目录:"+filePath);

            string str = "获取文件的全路径:" + Path.GetFullPath(filePath);   //-->C:\JiYF\BenXH\BenXHCMS.xml
            Console.WriteLine(str);
            str = "获取文件所在的目录:" + Path.GetDirectoryName(filePath); //-->C:\JiYF\BenXH
            Console.WriteLine(str);
            str = "获取文件的名称含有后缀:" + Path.GetFileName(filePath);  //-->BenXHCMS.xml
            Console.WriteLine(str);
            str = "获取文件的名称没有后缀:" + Path.GetFileNameWithoutExtension(filePath); //-->BenXHCMS
            Console.WriteLine(str);
            str = "获取路径的后缀扩展名称:" + Path.GetExtension(filePath); //-->.xml
            Console.WriteLine(str);
            str = "获取路径的根目录:" + Path.GetPathRoot(filePath); //-->C:\
            Console.WriteLine(str);
            Console.ReadKey();
        }
    }

创建文件

          //path是完整路径,要包含文件的后缀名
            string path = @"C:\1.txt";
            //判断文件是否存在,不存在就创建
            if (!File.Exists(path))
            {
                //创建一个 UTF-8 编码text文件
                File.CreateText(path);

                //创建一个文件
                //File.Create(path);
            }

写入文本文件

using System.IO;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            //写入文本,不是追加,是清空在写入
            string path = @"C:\1.txt";
            string[] lines = { "First line", "Second line"};
            File.WriteAllLines(path, lines);
            File.WriteAllText(path, "AAAAAAAAAAAAAAAA");

            //追加写入文本
            using (StreamWriter sw = new StreamWriter(path, true))
            {
                sw.WriteLine("Fourth line");
            }
            using (StreamWriter sw = File.AppendText(path))
            {
                sw.Write(12345);
            }

        }
    }
}

文件流读写

using var stream = File.OpenRead("path");
byte[] bytes = System.IO.File.ReadAllBytes("path");
File.WriteAllBytes("path", File.ReadAllBytes("path"));

方法

public Stream FileToStream(string fileFullName)
        {
            using (FileStream fs = new FileStream(fileFullName, FileMode.OpenOrCreate))
            {
                byte[] bytes = new byte[fs.Length];
                fs.Read(bytes, 0, bytes.Length);
                return new MemoryStream(bytes);
            }
        }

        public void WriteFile(string fileFullName, byte[] bytes)
        {
            if (bytes == null)
                return;
            using (FileStream fs = new FileStream(fileFullName, FileMode.OpenOrCreate))
            {
                fs.Write(bytes, 0, bytes.Length);
            }

               // 第二种
                using (MemoryStream m = new MemoryStream(bytes))
                using (FileStream fs = new FileStream(fileFullName, FileMode.OpenOrCreate))
                {
                    m.WriteTo(fs);
                }

        }

获取包含该字符串所有文件路径

public List<string> GetFilebySeachFile(string path, string str)
{
    return Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Where(filePath => File.ReadAllText(filePath).Contains(str)).ToList();
}

Stream流

Stream 和 byte[] 互转

        /// <summary>
        /// 将 Stream 转成 byte[]
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public byte[] StreamToBytes(Stream stream)
        {
            if (stream is MemoryStream)
            {
                return ((MemoryStream)stream).ToArray();
            }
            using MemoryStream ms = new MemoryStream();
            stream.CopyTo(ms);
            return ms.ToArray();
        }

        /// <summary>
        /// 将 byte[] 转成 Stream
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public Stream BytesToStream(byte[] bytes)
        {
            return new MemoryStream(bytes);
        }

byte[] 和String互转

var stringObject = System.Text.Encoding.UTF8.GetString(byte[]);
var bytesObject = System.Text.Encoding.UTF8.GetBytes(stringObject);
posted @ 2019-12-24 12:10  雨水的命运  阅读(1114)  评论(0编辑  收藏  举报