• C# 文件和文件夹操作


    一、文件操作

    1、File类的常用静态方法:

    • void AppendAllText(string path, string contents),将文本contents附加到文件path中
    • bool Exists(string path)判断文件path是否存在
    • string[] ReadAllLines(string path) 读取文本文件到字符串数组中
    • string ReadAllText(string path) 读取文本文件到字符串中
    • void WriteAllText(string path, string contents)将文本contents保存到文件path中,会覆盖旧内容。
    • WriteAllLines(string path,string[] contents),将字符串数组逐行保存到文件path中,会覆盖旧内容。
    • Copy(参数)方法:复制文件
    • Exists(string path):确定指定文件是否存在
    • Delete(string path):删除指定的文件,如果指定的文件不存在,则不引发异常
    • GetAttributes(string path):获取在此路径上的文件属性
    • File.SetAttributes(string path,FileAttributes fileAttributes):设置指定路径上的文件属性
    • GetCreationTime(string path):返回指定文件或目录的创建日期和时间

    FileInfo类和File类的功能类似,不同的是使用FileInfo类必须实例化对象;如需调用一系列方法,FileInfo类效率更高、更简单(由于File类的静态方法在使用时都会进行安全检查)

    二、目录操作
    1、Directory类的常用静态方法:(目录就是文件夹)

    • void Delete(string path, bool recursive):删除目录, recursive表示是否递归删除,如果recursive为false则只能删除空目录
    • bool Exists(string path) :判断目录是否存在
    • Move(string sourceDirName,string destDirName):移动
    • CreateDirectory(string path):创建文件夹
    • string[] GetDirectories(string path):得到一个目录下的子目录
    • string[] GetDirectories(string path, string searchPattern, SearchOption searchOption):通配符查找目录下的子目录
    • static string[] GetFiles(string path):得到指定目录下的文件名称数组
    • string[] GetFiles(string path, string searchPattern, SearchOption searchOption):通配符查找目录下的文件
    • DirectoryInfo GetParent(string path):得到目录的父目录
    • GetDirectories():获取当前目录的子目录的名称数组
    • GetCurrentDirectory():获取应用程序的当前目录
    • GetDorectoryRoot(string path):获取根目录

    DirectoryInfo类

      • DirectoryInfo[] GetDirectories():获取当前目录的子目录的对象数组
      • FileInfo[] GetFiles():得到当前目录下文件列表(FileInfo对象数组)
      • FileSystemInfo[] GetFileSystemInfos():返回表示某个目录中所有文件和子目录的强类型 FileSystemInfo 项的数组。
      •  2、判断该路径是文件还是文件夹

        复制代码
        string path = "D:\test.txt";
        // 方式一
        if (File.GetAttributes(path).CompareTo(FileAttributes.Directory) == 0)
        {
            Console.WriteLine("文件夹");
        }
        else
        {
            Console.WriteLine("文件");
        }
        // 方式二
        if (File.Exists(path))
        {
            Console.WriteLine("文件");
        }
        else if (Directory.Exists(path))
        {
            Console.WriteLine("文件夹");
        }
        复制代码

        3、创建目录、复制目录和删除目录

        复制代码
                /// <summary>
                /// 创建目录,可以直接Directory.CreateDirctory(string dirPath),或使用以下方法
                /// </summary>
                /// <param name="path"></param>
                public static void CreateDirtory(string path)
                {
                    if (!File.Exists(path))
                    {
                        string[] dirArray = path.Split('\');
                        string temp = string.Empty;
                        for (int i = 0; i < dirArray.Length - 1; i++)
                        {
                            temp += dirArray[i].Trim() + "\";
                            if (!Directory.Exists(temp))
                                Directory.CreateDirectory(temp);
                        }
                    }
                }
        
                /// <summary>
                /// 文件夹的复制
                /// </summary>
                /// <param sourceDir="string">要复制的原路径</param>
                /// <param targetDir="string">要复制的目的路径</param>
                /// <param name="overwrite">若为true,则允许覆盖现有文件;否则为false</param>
                /// <param name="copySubDir">是否复制子目录</param>
                public static void DirectoryCopy(string sourceDirPath, string targetDirPath, bool overwrite, bool copySubDir)
                {
               // 如果目录路径不是以路径符“”结尾,则在目录路径后加上路径符“”
        if (sourceDirPath[sourceDirPath.Length - 1] != Path.DirectorySeparatorChar)
        sourceDirPath += Path.DirectorySeparatorChar; DirectoryInfo sourceDirInfo = new DirectoryInfo(sourceDirPath); try { if (!sourceDirInfo.Exists)//判断所指的文件或文件夹是否存在 { return; } if (!Directory.Exists(targetDirPath)) { Directory.CreateDirectory(targetDirPath); } // 获取文件夹中所有文件和文件夹 FileSystemInfo[] sourceFiles = sourceDirInfo.GetFileSystemInfos(); // 对单个FileSystemInfo进行判断,如果是文件夹则进行递归操作 foreach (FileSystemInfo sourceFileSys in sourceFiles) { FileInfo file = sourceFileSys as FileInfo; if (file != null) // 如果是文件的话,进行文件的复制操作 { string targetFilePath = Path.Combine(targetDirPath, file.Name); if (File.Exists(targetFilePath) && overwrite) { File.SetAttributes(targetFilePath, FileAttributes.Normal); } file.CopyTo(targetFilePath, overwrite); // 将文件复制到指定的路径中 } else { if (copySubDir) { DirectoryCopy(sourceFileSys.FullName, Path.Combine(targetDirPath, sourceFileSys.Name), overwrite, copySubDir); } } } } catch (Exception ex) { throw ex; } } /// <summary> /// 删除指定的目录 /// </summary> /// <param name="dirPath">目录路径</param> /// <param name="isDelSelf">是否删除本身:true为删除指定目录,false为删除指定目录下的所有目录、子目录和文件</param> public static void DeleteDirectory(string dirPath, bool isDelSelf) { if (Directory.Exists(dirPath)) { if (isDelSelf) { Directory.Delete(dirPath, true); } else { foreach (string content in Directory.GetFileSystemEntries(dirPath)) { if (Directory.Exists(content)) Directory.Delete(content, true); else if (File.Exists(content)) File.Delete(content); } } } }
        复制代码

         三、文件路径

         Path类常用静态方法:

        • string ChangeExtension(string path, string extension) :
          •   修改文件的后缀,“修改”支持字符串层面的,没有真的给文件改名,如: string s = Path.ChangeExtension(@"C: empF3.png", "jpg")
        • string Combine(string path1, string path2):将两个路径合成一个路径,比用+好,可以方便解决是不是加斜线的问题,自动处理路径分隔符的问题
          •   string s = Path.Combine(@"c: emp","a.jpg")
        • string GetDirectoryName(string path) :得到文件的路径名。Path.GetDirectoryName(@"c: empa.jpg")
        • string GetExtension(string path) 得到文件的扩展名
        • string GetFileName(string path) 得到文件路径的文件名部分
        • string GetFileNameWithoutExtension(string path) 得到去除扩展名的文件名
        • string GetFullPath(string path) 得到文件的全路径。”.”当前路径,”..”上一级路径,”....”上一级的上一级
        • string GetTempFileName()  得到一个唯一的临时文件名
        • string GetTempPath() 得到临时文件夹的路径


        得到当前exe的路径。Assembly.GetExecutingAssembly().Location得到exe的全路径,Path.GetDirectoryName得到目录路径,不要用Directory.GetCurrentDirectory(),这个可能会变(使用OpenFileDialog或者SetCurrentDirectory())。
        AppDomain.CurrentDomain.BaseDirectory;  // 获取当前程序的目录
        Application.StartupPath // 获取当前程序的目录
        System.Environment.CurrentDirectory // 获取当前程序的目录,与Directory.GetCurrentDirectory()一样可能会变(使用OpenFileDialog或者SetCurrentDirectory())。参考:http://www.cnblogs.com/mayswind/archive/2013/06/12/3119570.html

  • 相关阅读:
    minGw编译器记录
    也来小谈jsonP
    [struts2]2.3.14 jsonplugin 存在bug<java.lang.NoSuchFieldException: DEFAULT_PARAM>
    年学习进度简记【2012】
    征服ExtJs那棵树(ExtJs官方开发手册汉语详解TreePanel)
    html 和ExtJs 搭建背景音乐 开发
    复习整理2
    MSChartHelpe
    DataToExcel
    如何将一个类型在FOREACH中使用
  • 原文地址:https://www.cnblogs.com/DonAndy/p/5921116.html
Copyright © 2020-2023  润新知