C# IO 相关功能整合

目录

删除文件和删除文件夹

拷贝文件到另一个目录

保存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.mfbz.cn/a/48455.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

8款常用系统镜像烧录软件

系统烧录软件是一种用于将操作系统或其他软件程序安装到嵌入式系统、嵌入式设备或存储设备中的工具。它通常用于将预先编译好的二进制文件或源代码烧录到硬件设备的非易失性存储器中&#xff0c;例如闪存芯片、EEPROM、EPROM或其他存储介质。系统烧录软件提供了一个便捷的方式&…

matplotlib

目录 plot bar pie plot plot可以绘制点图和线图 ?plt.plot #使用?查看plot详细信息 x[1,2,3,4,5] y[16,17,18,19,20] plt.plot(x,y) import numpy as np xnp.arange(0,10) yx*x plt.plot(x,y) xnp.arange(5,15,0.1) ynp.sin(x) plt.plot(x,y,ro) #red circle markers p…

vs2013 32位 编译的 dll,重新用vs2022 64位编译,所遇问题记录

目录 一、vs2013 32 DLL 转 VS2022 64 DLL 所遇问题 1、 LNK2038: 检测到“_MSC_VER”的不匹配项: 值“1800”不匹配值“1900” 2、原先VS2013 现在 VS2022 导致的vsnprintf 重定义问题 3、 无法解析的外部符号 __vsnwprintf_s 4、无法解析的外部符号__imp__CertFreeC…

在线平面设计工具盘点,提升效率首选

在移动应用程序或网页UI设计项目中&#xff0c;在线平面图工具是必不可少的。市场上的在线平面图工具绘制软件丰富多样&#xff0c;层出不穷。作为一名UI设计师&#xff0c;有必要了解哪些在线平面图工具既简单又专业。本文将分享6种在线平面图工具&#xff0c;每种在线平面图工…

199. 二叉树的右视图

给定一个二叉树的 根节点 root&#xff0c;想象自己站在它的右侧&#xff0c;按照从顶部到底部的顺序&#xff0c;返回从右侧所能看到的节点值。 示例 1: 输入: [1,2,3,null,5,null,4] 输出: [1,3,4] 示例 2: 输入: [1,null,3] 输出: [1,3] 示例 3: 输入: [] 输出: [] 提示…

力扣算法数学类—剑指 Offer 62. 圆圈中最后剩下的数字

目录 剑指 Offer 62. 圆圈中最后剩下的数字 题目背景&#xff1a; 题解&#xff1a; 代码&#xff1a; 结果&#xff1a; 剑指 Offer 62. 圆圈中最后剩下的数字 题目背景&#xff1a; 这是著名的约瑟夫环问题 这个问题是以弗拉维奥约瑟夫命名的&#xff0c;他是1世纪的一名…

【2023最新教程】6个步骤从0到1开发自动化测试框架(0基础也能看懂)

一、序言 随着项目版本的快速迭代、APP测试有以下几个特点&#xff1a; 首先&#xff0c;功能点多且细&#xff0c;测试工作量大&#xff0c;容易遗漏&#xff1b;其次&#xff0c;代码模块常改动&#xff0c;回归测试很频繁&#xff0c;测试重复低效&#xff1b;最后&#x…

机器学习——样本不均衡学习

1、样本不均衡定义 一般在分类机器学习中&#xff0c;每种类别的样本是均衡的&#xff0c;也就是不同目标值的样本总量是接近的&#xff0c;但是在很多场景下的样本没有办法做到理想情况&#xff0c;甚至部分情况本身就是不均衡情况&#xff1a; &#xff08;1&#xff09;很多…

SSL 证书过期巡检脚本

哈喽大家好&#xff0c;我是咸鱼 我们知道 SSL 证书是会过期的&#xff0c;一旦过期之后需要重新申请。如果没有及时更换证书的话&#xff0c;就有可能导致网站出问题&#xff0c;给公司业务带来一定的影响 所以说我们要每隔一定时间去检查网站上的 SSL 证书是否过期 如果公…

StackOverFlow刚刚宣布推出自己的AI产品!

StackOverFlow刚刚宣布要推出自己的AI产品&#xff01; OverflowAI是StackOverFlow即将推出自己AI产品的名字&#xff0c;据称也是以VSCode插件的形式&#xff0c;计划在8月发布。我们来看看都有些什么功能&#xff0c;通过目前的信息看&#xff0c;OverflowAI的主要功能就是&…

中断控制器的驱动解析

这里主要分析 linux kernel 中 GIC v3 中断控制器的代码(drivers/irqchip/irq-gic-v3.c)。 设备树 先来看下一个中断控制器的设备树信息&#xff1a; gic: interrupt-controller51a00000 {compatible "arm,gic-v3";reg <0x0 0x51a00000 0 0x10000>, /* GI…

机器学习笔记之优化算法(二)线搜索方法(方向角度)

机器学习笔记之优化算法——线搜索方法[方向角度] 引言回顾&#xff1a;线搜索方法从方向角度观察线搜索方法场景构建假设1&#xff1a;目标函数结果的单调性假设2&#xff1a;屏蔽步长 α k \alpha_k αk​对线搜索方法过程的影响假设3&#xff1a;限定向量 P k \mathcal P_k …

Transformer模型简单介绍

Transformer是一个深度学习模型。主要功能通俗的来说就是翻译。输入&#xff0c;处理&#xff0c;输出。 https://zhuanlan.zhihu.com/p/338817680 大牛写的很完整 目录 总框架Encoder输入部分注意力机制前馈神经网络 Decoder 总框架 Encoders: 编码器Decoders: 解码器 Encoder…

【node.js】01-fs读写文件内容

目录 一、fs.readFile() 读取文件内容 二、fs.writeFile() 向指定的文件中写入内容 案例&#xff1a;整理txt 需求&#xff1a; 代码&#xff1a; 一、fs.readFile() 读取文件内容 代码&#xff1a; //导入fs模块&#xff0c;从来操作文件 const fs require(fs)// 2.调…

Vue+ElementUI操作确认框及提示框的使用

在进行数据增删改查操作中为保证用户的使用体验&#xff0c;通常需要显示相关操作的确认信息以及操作结果的通知信息。文章以数据的下载和删除提示为例进行了简要实现&#xff0c;点击下载以及删除按钮&#xff0c;会出现对相关信息的提示&#xff0c;操作结果如下所示。 点击…

第十章:重新审视扩张卷积:一种用于弱监督和半监督语义分割的简单方法

0.摘要 尽管取得了显著的进展&#xff0c;弱监督分割方法仍然不如完全监督方法。我们观察到性能差距主要来自于它们在从图像级别监督中学习生成高质量的密集目标定位图的能力有限。为了缓解这样的差距&#xff0c;我们重新审视了扩张卷积[1]并揭示了它如何以一种新颖的方式被用…

【云原生】Docker容器资源限制(CPU/内存/磁盘)

目录 ​编辑 1.限制容器对内存的使用 2.限制容器对CPU的使用 3.block IO权重 4.实现容器的底层技术 1.cgroup 1.查看容器的ID 2.在文件中查找 2.namespace 1.Mount 2.UTS 3.IPC 4.PID 5.Network 6.User 1.限制容器对内存的使用 ⼀个 docker host 上会运⾏若⼲容…

【Python入门系列】第十八篇:Python自然语言处理和文本挖掘

文章目录 前言一、Python常用的NLP和文本挖掘库二、Python自然语言处理和文本挖掘1、文本预处理和词频统计2、文本分类3、命名实体识别4、情感分析5、词性标注6、文本相似度计算 总结 前言 Python自然语言处理&#xff08;Natural Language Processing&#xff0c;简称NLP&…

PLC学习的步骤与重点:

熟悉基础元器件的原理和使用方法&#xff1a;了解按钮、断路器、继电器、接触器、24V开关电源等基础元器件的原理和使用方法&#xff0c;并能够应用它们来实现简单的逻辑电路&#xff0c;例如电机的正反转和单按钮的启停控制。 掌握PLC的接线方法&#xff1a;了解PLC的输入输出…

【微服务架构设计】微服务不是魔术:处理超时

微服务很重要。它们可以为我们的架构和团队带来一些相当大的胜利&#xff0c;但微服务也有很多成本。随着微服务、无服务器和其他分布式系统架构在行业中变得更加普遍&#xff0c;我们将它们的问题和解决它们的策略内化是至关重要的。在本文中&#xff0c;我们将研究网络边界可…
最新文章