首页 > 编程语言 >【C#】文件操作

【C#】文件操作

时间:2024-10-12 09:00:31浏览次数:1  
标签:files 文件 Exception string C# List 操作 new

创建文件夹

if (!Directory.Exists(desPath))
{
    try
    {
        Directory.CreateDirectory(desPath);
    }
    catch (Exception e)
    {
        throw new Exception("创建目标目录失败:" + e.Message);
    }
}

创建文件

using (System.IO.StreamWriter file = new System.IO.StreamWriter(filePath))
{
    JObject jobject = JObject.Parse(json);
    file.Write(jobject.ToString());
}

读取文件夹中所有指点文件目录

List<string> fileNameList = new List<string>();
try
{
    DirectoryInfo directoryInfo = new DirectoryInfo(folder);
    FileInfo[] files = directoryInfo.GetFiles("*.json");

    foreach (var item in files)
    {
        fileNameList.Add(item.Name);
    }
}
catch (Exception e)
{
    throw new Exception("获取文件路径错误:" + e.Message);
}
return fileNameList;

复制文件

try
{
    //filepath需要被复制的文件路径;desFile复制文件的目标路径;是否重写
    File.Copy(filepath, desFile, true);
}
catch (Exception e)
{
    Debug.Log($"复制文件 {filepath_full} 失败:" + e.Message);
}

读取文件

使用Using保证文件读取之后,文件流被关闭,防止进程占用

string filePath = folderPath + "/" + item;
using (StreamReader file = File.OpenText(filePath))
using (JsonTextReader reader = new JsonTextReader(file))
{
    JObject res = (JObject)JToken.ReadFrom(reader);
}

删除文件夹

删除文件时,出现报错:文件在其他进程被占用,检查创建/打开文件时,是否关闭文件流

if (Directory.Exists(folderPath))
{
    try
    {
        //删除文件夹,即使是空文件夹,也会被删除
        Directory.Delete(folderPath, true);

    }
    catch (Exception e)
    {
        string str = "errer :" + e.Message;
        throw new Exception(str);
    }
}

删除文件夹中的指定文件

if (Directory.Exists(folderPath))
{
    DirectoryInfo direction = new DirectoryInfo(folderPath);
    FileInfo[] files = direction.GetFiles("*", SearchOption.AllDirectories);
    for (int i = 0; i < files.Length; ++i)
    {
        if (files[i].Name.Contains(".json") || files[i].Name.Contains(".xml"))
        {
            File.Delete(folderPath + "/" + files[i].Name);
        }
    }
}

获取某格式的所有文件名

private List<string> GetAllFilesName(string folder)
{
    List<string> fileNameList = new List<string>();
    try
    {
        IsWrong = false;
        DirectoryInfo directoryInfo = new DirectoryInfo(folder);
        FileInfo[] files = directoryInfo.GetFiles("*.json");

        foreach (var item in files)
        {
            fileNameList.Add(item.Name);
        }
    }
    catch (Exception ex)
    {
        IsWrong = true;
        MessageBox.Show("获取文件路径错误\n" + ex);
    }
    return fileNameList;
}

读取TxT文本

Read 逐个字符读

ReadLine逐行读

ReadToEnd从头读到尾

private List<string> ReadTxtFile(string folder, string fileName){
    List<string> res = new List<string>();
    string filePath = System.IO.Path.Combine(folder + "/" + fileName);
    using (StreamReader sr = new StreamReader(txtfilePath, System.Text.Encoding.UTF8)){
        string line;
        while((line==sr.ReadLine())!=null){
            res.Add(line);
        }
        sr.Close();
    }
    return res;
}

写入TxT文本

Write 写入

WriteLine写入,并在最后加入换行符“\r\n”

Flush 清理缓冲区,并将缓冲区输入存入文件

StreamWriter (string path) 写入的新内容将替代原本的内容

StreamWriter ( string path, bool append ) append=true是追加内容

private void WriteTxtFile(string folder, string fileName, List<string> contents){
    string filePath = System.IO.Path.Combine(folder + "/" + fileName);
    using (StreamWriter sw = new StreamWriter(txtfilePath, System.Text.Encoding.UTF8)){
        foreach(var content in contents){
            sw.WriteLine(content);
        }
        sw.Flush();
        sw.Close();
    }
}

标签:files,文件,Exception,string,C#,List,操作,new
From: https://www.cnblogs.com/sitarblogs/p/18459772

相关文章

  • Java中class对象的学习
    Class对象目录Class对象获取class对象的三种方法获取类的各种信息获取类名获取类修饰符获取包的信息获取父类的class对象获取接口信息构造函数Constructor两种创建对象的方式使用Class.forName()加载类并创建对象使用Class.forName()加载类,并调用特定的构造器获取class对象的三......
  • Invicti v24.10.0 for Windows - Web 应用程序安全测试
    Invictiv24.10.0forWindows-Web应用程序安全测试InvictiStandardv24.10.0–8October2024请访问原文链接:https://sysin.org/blog/invicti/查看最新版。原创作品,转载请保留出处。作者主页:sysin.orgInvicti是一种自动化但完全可配置的Web应用程序安全扫描程序,使......
  • Python知识点:基于Python技术,如何使用ROS与Python进行机器人操作
    开篇,先说一个好消息,截止到2025年1月1日前,翻到文末找到我,赠送定制版的开题报告和任务书,先到先得!过期不候!使用ROS与Python进行机器人操作的技术详解机器人操作是机器人学中的一个核心领域,它涉及到对机器人的运动控制、传感器数据处理以及自动化任务的实现。ROS(RobotOperat......
  • 南沙C++信奥赛陈老师解一本通题 1939:【07NOIP普及组】纪念品分组
    ​ 【题目描述】元旦快到了,校学生会让乐乐负责新年晚会的纪念品发放工作。为使得参加晚会的同学所获得的纪念品价值相对均衡,他要把购来的纪念品根据价格进行分组,但每组最多只能包括两件纪念品,并且每组纪念品的价格之和不能超过一个给定的整数。为了保证在尽量短的时间内发完......
  • 【命令操作】查看和分析系统各类日志--journalctl
    原文链接:【命令操作】查看和分析系统各类日志–journalctl|统信|麒麟|方德Hello,大家好啊!今天给大家带来一篇关于Linux系统上journalctl命令详解的文章。journalctl是systemd的日志查看工具,用于查看和管理系统日志,包括内核消息、服务日志、用户日志等。通过journalctl......
  • sicp每日一题[2.42]
    这道题太难了,我自己只完成了empty-board这一个定义,其他的函数即使看了别人的答案也研究了半天才搞明白。。;board-size指的是正方形棋盘的长(define(queensboard-size)(define(queen-colsk)(if(=k0)(listempty-board)(filter......
  • 题解 QOJ5048【[ECFinal19K] All Pair Maximum Flow】
    题目描述给你一个\(n\)个点\(m\)条边的图,它是平面上的正\(n\)边形和一些对角线,节点按逆时针方向编号为\(1\)到\(n\)。对角线只可能在节点处相交。每条边有一个容量,求每个点对之间的最大流的和。\(n\leq200000,m\leq400000\)。solution做法每次找出边权最小的边\(......
  • 【C#】Dictionary集合解决实际问题
    们将使用C#的Dictionary集合(它是一个键值对集合,类似于其他编程语言中的Map)来存储员工的ID和他们的薪水。我们将创建一个简单的控制台应用程序,用于添加员工、显示员工薪水以及更新员工薪水。首先,我们需要创建一个Employee类来存储员工的信息:publicclassEmployee{public......
  • 200号资源-源程序:(SCI论文+程序)使用多描述编码的状态估计外包传输网络------已提供下载
    ......
  • 文件管理方案参考 2024.10.12
    文件管理方案参考2024.10.12说明:此文档中的文件是指手机、平板电脑、笔记本电脑等电子设备在使用过程中新建、接收、重命名、移动、编辑的电子文件。例如:Word文档(.docx)、Excel表格(.xlsx)、Photoshop图片(.jpg)、酷我音乐盒无损音乐歌曲(.flac)、国语中字电影视频(.MP4)、视频教程(.AVI)。......