C# IO 相关功能整合

news2024/9/27 17:25:29

目录

删除文件和删除文件夹

拷贝文件到另一个目录

保存Json文件和读取Json文件

写入和读取TXT文件

打开一个弹框,选择 文件/文件夹,并获取路径

获取项目的Debug目录路径

获取一个目录下的所有文件集合

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

判断两个文件是否相同

判断文件路径或文件是否存在

判断一个路径是文件夹还是文件


删除文件和删除文件夹

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace 删除文件和文件夹
{
    class Program
    {
        static void Main(string[] args)
        {
            string path1 = Environment.CurrentDirectory + "\\MyTest";
            string path2 = Environment.CurrentDirectory + "\\新建文本文档.txt";
 
            //删除文件夹
            if (Directory.Exists(path1))
                Directory.Delete(path1, true);
 
            //删除文件
            if (File.Exists(path2))
                File.Delete(path2);
 
            Console.ReadKey();
        }
    }
}

拷贝文件到另一个目录

/// <summary>
/// 拷贝文件到新的目录,如果存在则覆盖
/// </summary>
/// <param name="path1">要拷贝的文件,不能是文件夹</param>
/// <param name="path2">新的路径,可以使用新的文件名,但不能是文件夹</param>
public static void CopyFile(string path1, string path2)
{
    //string path1 = @"c:\SoureFile.txt";
    //string path2 = @"c:\NewFile.txt";
    try
    {
        FileInfo fi1 = new FileInfo(path1);
        FileInfo fi2 = new FileInfo(path2);
 
        //创建路径1文件
        //using (FileStream fs = fi1.Create()) { }
 
        if (!File.Exists(path1))
        {
            Console.WriteLine("要拷贝的文件不存在:" + path1);
            return;
        }
 
        //路径2文件如果存在,就删除
        //if (File.Exists(path2))
        //{
        //    fi2.Delete();
        //}
 
        //path2 替换的目标位置
        //true 是否替换文件,true为覆盖之前的文件
        fi1.CopyTo(path2,true);
    }
    catch (IOException ioex)
    {
        Console.WriteLine(ioex.Message);
    }
}

另一种

/// <summary>
/// 拷贝文件到另一个文件夹下
/// </summary>
/// <param name="sourceName">源文件路径</param>
/// <param name="folderPath">目标路径(目标文件夹)</param>
public void CopyToFile(string sourceName, string folderPath)
{
    //例子:
    //源文件路径
    //string sourceName = @"D:\Source\Test.txt";
    //目标路径:项目下的NewTest文件夹,(如果没有就创建该文件夹)
    //string folderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "NewTest");
 
    if (!Directory.Exists(folderPath))
    {
        Directory.CreateDirectory(folderPath);
    }
 
    //当前文件如果不用新的文件名,那么就用原文件文件名
    string fileName = Path.GetFileName(sourceName);
    //这里可以给文件换个新名字,如下:
    //string fileName = string.Format("{0}.{1}", "newFileText", "txt");
 
    //目标整体路径
    string targetPath = Path.Combine(folderPath, fileName);
 
    //Copy到新文件下
    FileInfo file = new FileInfo(sourceName);
    if (file.Exists)
    {
        //true 为覆盖已存在的同名文件,false 为不覆盖
        file.CopyTo(targetPath, true);
    }
}

保存Json文件和读取Json文件

/// <summary>
/// 将序列化的json字符串内容写入Json文件,并且保存
/// </summary>
/// <param name="path">路径</param>
/// <param name="jsonConents">Json内容</param>
private static void WriteJsonFile(string path, string jsonConents)
{
    using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, FileShare.ReadWrite))
    {
        fs.Seek(0, SeekOrigin.Begin);
        fs.SetLength(0);
        using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
        {
            sw.WriteLine(jsonConents);
        }
    }
}
 
/// <summary>
/// 获取到本地的Json文件并且解析返回对应的json字符串
/// </summary>
/// <param name="filepath">文件路径</param>
/// <returns>Json内容</returns>
private string GetJsonFile(string filepath)
{
    string json = string.Empty;
    using (FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, FileShare.ReadWrite))
    {
        using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))
        {
            json = sr.ReadToEnd().ToString();
        }
    }
    return json;
}

写入和读取TXT文件

写入:

/// <summary>
/// 向txt文件中写入字符串
/// </summary>
/// <param name="value">内容</param>
/// <param name="isClearOldText">是否清除旧的文本</param>
private void Wriete(string value, bool isClearOldText = true)
{
    string path = "txt文件的路径";
    //是否清空旧的文本
    if (isClearOldText)
    {
        //清空txt文件
        using (FileStream stream = File.Open(path, FileMode.OpenOrCreate, FileAccess.Write))
        {
            stream.Seek(0, SeekOrigin.Begin);
            stream.SetLength(0);
        }
    }
    //写入内容
    using (StreamWriter writer = new StreamWriter(path, true))
    {
        writer.WriteLine(value);
    }
}

读取:

/// <summary>
/// 读取txt文件,并返回文件中的内容
/// </summary>
/// <returns>txt文件内容</returns>
private string ReadTxTContent()
{
    try
    {
        string s_con = string.Empty;
        // 创建一个 StreamReader 的实例来读取文件 
        // using 语句也能关闭 StreamReader
        using (StreamReader sr = new StreamReader("txt文件的路径"))
        {
            string line;
            // 从文件读取并显示行,直到文件的末尾 
            while ((line = sr.ReadLine()) != null)
            {
                s_con += line;
            }
        }
        return s_con;
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
        return null;
    }
}

打开一个弹框,选择 文件/文件夹,并获取路径

注意,选择文件和选择文件夹的用法不一样

选择文件夹

System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
dialog.Description = "请选择文件夹";
dialog.SelectedPath = "C:\\";
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    Console.WriteLine("选择了文件夹路径:" + dialog.SelectedPath);
}

选择文件

OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = true;//该值确定是否可以选择多个文件
dialog.Title = "请选择文件";
dialog.Filter = "所有文件(*.*)|*.*";
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    Console.WriteLine("选择了文件路径:" + dialog.FileName);
}

限制文件的类型

例1:

OpenFileDialog dialog = new OpenFileDialog();
//该值确定是否可以选择多个文件
dialog.Multiselect = false;
dialog.Title = "请选择文件";
dialog.Filter = "stp文件|*.stp|step文件|*.STEP|所有文件|*.*";
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    string path = dialog.FileName;
}

例2:

OpenFileDialog dialog = new OpenFileDialog();
//该值确定是否可以选择多个文件
dialog.Multiselect = false;
dialog.Title = "请选择文件";
dialog.Filter = "图像文件|*.jpg*|图像文件|*.png|所有文件|*.*";
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    string path = dialog.FileName;
}

保存文件

保存文件,用的是 SaveFileDialog 

代码

SaveFileDialog s = new SaveFileDialog();
s.Filter = "图像文件|*.jpg|图像文件|*.png|所有文件|*.*";//保存的文件扩展名
s.Title = "保存文件";//对话框标题
s.DefaultExt = "图像文件|*.jpg";//设置文件默认扩展名 
s.InitialDirectory = @"C:\Users\Administrator\Desktop";//设置保存的初始目录
if (s.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
   string path = s.FileName;
}

获取项目的Debug目录路径

控制台程序:

string path = Environment.CurrentDirectory;

Winform:

string path = Application.StartupPath;

WPF:

string path = AppDomain.CurrentDomain.BaseDirectory;

获取一个目录下的所有文件集合

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Test
{
    class Program
    {
        //文件夹列表
        private static List<string> DirectorysList = new List<string>();
        //文件列表
        private static List<string> FilesinfoList = new List<string>();
 
        static void Main(string[] args)
        {
            //路径
            string path1 = Environment.CurrentDirectory + "\\Test1";
 
            GetDirectoryFileList(path1);
 
            Console.ReadKey();
        }
 
        /// <summary>
        /// 获取一个文件夹下的所有文件和文件夹集合
        /// </summary>
        /// <param name="path"></param>
        private static void GetDirectoryFileList(string path)
        {
            DirectoryInfo directory = new DirectoryInfo(path);
            FileSystemInfo[] filesArray = directory.GetFileSystemInfos();
            foreach (var item in filesArray)
            {
                //是否是一个文件夹
                if (item.Attributes == FileAttributes.Directory)
                {
                    DirectorysList.Add(item.FullName);
                    GetDirectoryFileList(item.FullName);
                }
                else
                {
                    FilesinfoList.Add(item.FullName);
                }
            }
        }
    }
}

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

代码:

using System;
using System.IO;
 
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();
    }
}

读取当前的文件夹名

using System;
using System.Collections.Generic;
using System.IO;
 
namespace ListTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string fileDir = Environment.CurrentDirectory;
            DirectoryInfo dirInfo = new DirectoryInfo(fileDir);
            string currentDir = dirInfo.Name; 
            Console.WriteLine(currentDir);
 
            string dirName = System.IO.Path.GetFileNameWithoutExtension(fileDir);
            Console.WriteLine(dirName);
 
            Console.ReadKey();
        }
    }
}

运行:

判断两个文件是否相同

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
 
namespace 判断两个文件是否相同
{
    class Program
    {
        static void Main(string[] args)
        {
            //路径
            string path1 = Environment.CurrentDirectory + "\\Test1\\文件1.txt";
            string path2 = Environment.CurrentDirectory + "\\Test2\\文件1.txt";
 
            bool valid = isValidFileContent(path1, path2);
            Console.WriteLine("这两个文件是否相同:" + valid);
 
            Console.ReadKey();
        }
 
        public static bool isValidFileContent(string filePath1, string filePath2)
        {
            //创建一个哈希算法对象
            using (HashAlgorithm hash = HashAlgorithm.Create())
            {
                using (FileStream file1 = new FileStream(filePath1, FileMode.Open), file2 = new FileStream(filePath2, FileMode.Open))
                {
                    byte[] hashByte1 = hash.ComputeHash(file1);//哈希算法根据文本得到哈希码的字节数组
                    byte[] hashByte2 = hash.ComputeHash(file2);
                    string str1 = BitConverter.ToString(hashByte1);//将字节数组装换为字符串
                    string str2 = BitConverter.ToString(hashByte2);
                    return (str1 == str2);//比较哈希码
                }
            }
        }
    }
}

判断文件路径或文件是否存在

判断文件夹是否存在:

string path = Application.StartupPath + "\\新建文件夹";
if (!System.IO.Directory.Exists(path))
{
    System.IO.Directory.CreateDirectory(path);//不存在就创建目录
}

判断文件是否存在:

string path = Application.StartupPath + "\\新建文件夹\\test.txt"
if(System.IO.File.Exists(path)) 
{
    Console.WriteLine("存在该文件");
}
else
{
    Console.WriteLine("不存在该文件");
}

判断一个路径是文件夹还是文件

方式1

/// <summary>
/// 判断目标是文件夹还是目录(目录包括磁盘)
/// </summary>
/// <param name="filepath">路径</param>
/// <returns>返回true为一个文件夹,返回false为一个文件</returns>
public static bool IsDir(string filepath)
{
    FileInfo fi = new FileInfo(filepath);
    if ((fi.Attributes & FileAttributes.Directory) != 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

方式2

if (File.Exists(add_file))
{
    Console.WriteLine("是文件");
}
else if (Directory.Exists(targetPath))
{
    Console.WriteLine("是文件夹");
}
else
{
    Console.WriteLine("都不是");
}

end

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/805222.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

原生js vue react通用的递归函数

&#x1f642;博主&#xff1a;锅盖哒 &#x1f642;文章核心&#xff1a;原生js vue react通用的递归函数 目录大纲 1.递归函数的由来 2.代码逻辑 1.递归函数的由来 递归函数的由来可以追溯到数学中的递归概念和数学归纳法。 在数学中&#xff0c;递归是指通过定义基本情况和…

windows切换php版本以及composer

前提 安装php8.2 安装Php7.4 下载 nts是非线程安全的&#xff0c;这里选择线程安全的&#xff0c;选择64位 解压缩 修改系统环境变量 修改为php-7的 cmd中输入php -v查看 找到composer存放路径C:\ProgramData\ComposerSetup\bin 将三个文件复制到php目录下 重启电脑…

flink采用thrift读取tablets一个天坑

原先的配置 [INFO] StarRocksSourceBeReader [open Scan params.mem_limit 8589934592 B] [INFO] StarRocksSourceBeReader [open Scan params.query-timeout-s 600 s] [INFO] StarRocksSourceBeReader [open Scan params.keep-alive-min 100 min] [INFO] StarRocksSourceBeRea…

中间件安全-CVE漏洞复现-Docker+Websphere+Jetty

中间件-Docker Docker容器是使用沙盒机制&#xff0c;是单独的系统&#xff0c;理论上是很安全的&#xff0c;通过利用某种手段&#xff0c;再结合执行POC或EXP&#xff0c;就可以返回一个宿主机的高权限Shell&#xff0c;并拿到宿主机的root权限&#xff0c;可以直接操作宿主机…

【图论】Prim算法

一.介绍 Prim算法是一种用于解决最小生成树问题的贪心算法。最小生成树问题是指在一个连通无向图中找到一个生成树&#xff0c;使得树中所有边的权重之和最小。 Prim算法的基本思想是从一个起始顶点开始&#xff0c;逐步扩展生成树&#xff0c;直到覆盖所有顶点。具体步骤如下…

【Ansible】

目录 一、Ansible简介二、ansible 环境安装部署1、管理端安装 ansible 三、ansible 命令行模块&#xff08;重点&#xff09;1&#xff0e;command 模块2&#xff0e;shell 模块3、cron 模块4&#xff0e;user 模块5&#xff0e;group 模块6&#xff0e;copy 模块&#xff08;重…

后台管理系统中刷新业务功能的实现

实现 由于刷新业务涉及路由通信所以在store/pinia创建全局变量refresh state:()>{return{// 是否刷新refresh:false,}},在header组件中是为刷新按钮绑定点击实现并对refresh取反操作 <el-button type"default" click"refresh!refresh" icon"R…

LaTex使用技巧20:LaTex修改公式的编号和最后一行对齐

写论文发现公式编号的格式不对&#xff0c;要求是如果是多行的公式&#xff0c;公式编号和公式的最后一行对齐。 我原来使用的是{equation}环境。 \begin{equation} \begin{aligned} a&bc\\ &cd \end{aligned} \end{equation}公式的编号没有和最后一行对齐。 查了一…

No101.精选前端面试题,享受每天的挑战和学习(Promise)

文章目录 1. 解释什么是Promise&#xff0c;并简要说明它的作用和优势。2. Promise有几种状态&#xff1f;每种状态的含义是什么&#xff1f;3. 解释Promise链式调用&#xff08;chaining&#xff09;的作用和如何实现。4. 如何捕获和处理Promise链中的错误&#xff1f;5. 解释…

【2023.7.29】本文用于自己写文章时查看Markdown编辑器语法

这里写自定义目录标题 欢迎使用Markdown编辑器新的改变功能快捷键合理的创建标题&#xff0c;有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中、居左、居右SmartyPants 创建一个自定义列表如何创建一个…

【C语言学习——————动态内存管理】

文章目录 一、什么是动态内存管理二、动态内存函数的介绍 1.malloc函数的介绍2.calloc函数的介绍3.realloc函数的介绍三、free函数的介绍 一.什么是动态内存管理 我们知道数据都是在内存中进行储存的&#xff0c;但是如果我们需要调用内存&#xff0c;我们可以通过定义一个变量…

实现哈希表

一&#xff1a;什么是哈希表&#xff1f; 哈希表是一种常见的数据结构&#xff0c;它通过将键映射到值的方式来存储和组织数据。具体来说&#xff0c;哈希表使用哈希函数将每个键映射到一个索引&#xff08;在数组中的位置&#xff09;&#xff0c;然后将该键值对存储在该索引处…

IOS + Appium自动化教程

前言 项目闲置下来了&#xff0c;终于抽空有时间搞自动化了&#xff0c;看了下网上的教程基本通篇都是android自动化的介绍 &#xff0c;ios自动化方面的内容网上简介的少之可怜。由于本人对ios自动化也是第一次做&#xff0c;甚至对苹果电脑的使用都不太熟悉&#xff0c;花了大…

微信小程序,商城底部工具栏的实现

效果演示&#xff1a; 前提条件&#xff1a; 去阿里云矢量图标&#xff0c;下载8个图标&#xff0c;四个黑&#xff0c;四个红&#xff0c;如图&#xff1a; 新建文件夹icons&#xff0c;把图标放到该文件夹&#xff0c;然后把该文件夹移动到该项目的文件夹里面。如图所示 app…

vue3如何封装接口

&#x1f642;博主&#xff1a;锅盖哒 &#x1f642;文章核心&#xff1a;如何封装接口 目录 前言 1.首先&#xff0c;安装并导入axios库。你可以使用npm或yarn来安装&#xff1a; 2.创建一个api.js文件来管理接口封装&#xff1a; 3.在Vue组件中使用封装的接口&#xff1…

【雕爷学编程】MicroPython动手做(02)——尝试搭建K210开发板的IDE环境4

7、使用串口工具 &#xff08;1&#xff09;连接硬件 连接 Type C 线&#xff0c; 一端电脑一端开发板 查看设备是否已经正确识别&#xff1a; 在 Windows 下可以打开设备管理器来查看 如果没有发现设备&#xff0c; 需要确认有没有装驱动以及接触是否良好 &#xff08;2&a…

Ubuntu更改虚拟机网段(改成桥接模式无法连接网络)

因为工作需要&#xff0c;一开始在安装vmware和虚拟机时&#xff0c;是用的Nat网络。 现在需要修改虚拟机网段&#xff0c;把ip设置成和Windows端同一网段&#xff0c;我们就要去使用桥接模式。 环境&#xff1a; Windows10、Ubuntu20.04虚拟机编辑里打开虚拟网络编辑器&#…

安装Harbor

前言 Harbor是一个用于存储和分发Docker镜像的企业级Registry服务器&#xff0c;虽然Docker官方也提供了公共的镜像仓库&#xff0c;但是从安全和效率等方面考虑&#xff0c;部署企业内部的私有环境Registry是非常必要的&#xff0c;Harbor和docker中央仓库的关系&#xff0c;…

第四章:Spring上

第四章&#xff1a;Spring上 4.1&#xff1a;Spring简介 Spring概述 官网地址&#xff1a;https://spring.io/。 Spring是最受欢迎的企业级的java应用程序开发框架&#xff0c;数以百万的来自世界各地的开发人员使用Spring框架来创建性能好、易于测试、可重用的代码。Spring框…

【多模态】18、ViLD | 通过对视觉和语言知识蒸馏来实现开集目标检测(ICLR2022)

文章目录 一、背景二、方法2.1 对新类别的定位 Localization2.2 使用 cropped regions 进行开放词汇检测2.3 ViLD 三、效果 论文&#xff1a;Open-vocabulary Object Detection via Vision and Language Knowledge Distillation 代码&#xff1a;https://github.com/tensorflo…