C# 文件操作(复制、移动、重命名、创建、打开、删除)

这篇具有很好参考价值的文章主要介绍了C# 文件操作(复制、移动、重命名、创建、打开、删除)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

目录

一、简介

二、创建文件

三、写入文件

四、读取文件

五、复制文件

六、移动文件

七、重命名文件

八、删除文件

结束


一、简介

C#中的IO(Input/Output)操作包括读取和写入文件、读取和写入流、以及操作目录和文件夹等。这些操作都可以通过System.IO命名空间中的类实现。下面对C# IO相关的类和操作进行介绍。

文件操作
File类
File类提供了对文件的创建、读取、写入、复制、移动、重命名和删除等操作。

StreamReader和StreamWriter类
StreamReader和StreamWriter类用于读取和写入文本文件。

目录和文件夹操作
Directory和DirectoryInfo类
Directory和DirectoryInfo类提供了对目录和文件夹的创建、移动、重命名和删除等操作。

二、创建文件

要创建一个文件,可以使用System.IO.File.Create()方法。该方法接受一个文件路径和一个可选的缓冲区大小作为参数,然后返回一个FileStream对象,该对象可用于写入文件。

代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 文件操作
{
    internal class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string filePath = @"E:\myFile.txt";
                FileStream fileStream = File.Create(filePath);
                fileStream.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("创建文件失败:" + ex.Message);
            }
            Console.WriteLine("创建文件成功!");
            Console.ReadKey();
        }
    }
}

打开E盘,文件是创建成功了,只是这个 txt 文件里没有任何内容

C# 文件操作(复制、移动、重命名、创建、打开、删除)

三、写入文件

写入文件可以使用下面方式:
1. File.WriteAllText(FilePath,String)
2. File.WriteAllText(FilePath, String,Encoding) ----指定编码
3. File.WriteAllLines(FilePath,String[])
4. File.WriteAllLines(FilePath,String[],Encoding) ----指定编码

前面两种写入的是一个字符串,后面两种写入的是一个字符串数组。

使用 File.WriteAllText 或 File.WriteAllLines 方法时,如果指定的文件路径不存在,会创建一个新文件;如果文件已经存在,则会覆盖原文件。

第一种:字符串的写入

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 文件操作
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string filePath = @"E:\myFile.txt";
            string content = "读取读取读取读取读取读取";
            //第一种
            //File.WriteAllText(filePath, content);
            //第二种
            File.WriteAllText(filePath, content, Encoding.UTF8);

            Console.ReadKey();
        }
    }
}

打开刚创建的 myFile.txt 文件:

C# 文件操作(复制、移动、重命名、创建、打开、删除)

第二种:多行字符串的写入

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 文件操作
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string filePath = @"E:\myFile.txt";
            string[] contentArr = { "dddd", "eeeeee" };

            //第一种
            //File.WriteAllLines(filePath, contentArr);
            //第二种
            File.WriteAllLines(filePath, contentArr, Encoding.UTF8);

            Console.ReadKey();
        }
    }
}

上面写入的字符串现在已经被覆盖了

C# 文件操作(复制、移动、重命名、创建、打开、删除)

上面写入字符串都会覆盖原有的内容,下面就介绍如何追加字符串。

第三种:追加字符串

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string filePath = @"E:\myFile.txt";
            string content = "423423423423";

            File.AppendAllText(filePath, content);

            Console.ReadKey();
        }
    }
}

filePath 路径这个文件如果没有,C# 会自动生成这个文件,运行后找到这个文件,就可以看到添加的内容

C# 文件操作(复制、移动、重命名、创建、打开、删除)

下面我将内容做一下更改,再次运行

namespace Test1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string filePath = @"E:\myFile.txt";
            string content = "dffsddgaadfasdfa";

            File.AppendAllText(filePath, content);

            Console.ReadKey();
        }
    }
}

我们重写打开 myFile.txt 这个文件,发现文字是追加上去了,但是并没有换行

C# 文件操作(复制、移动、重命名、创建、打开、删除)

其实换行也非常的简单,直接在字符串里加转义字符 \n 就行了

namespace Test1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string filePath = @"E:\myFile.txt";
            string content = "\n哇哈哈哈哈";

            File.AppendAllText(filePath, content);

            Console.ReadKey();
        }
    }
}

效果:

C# 文件操作(复制、移动、重命名、创建、打开、删除)

第四种:追加多行字符串

按上面的套路,添加多行当然也是可以的,不过用的方法名要换一个了

使用 File.AppendAllLines 来添加多行文字。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string filePath = @"E:\myFile.txt";
            string[] list = { "\n恭喜", "发财", "红包", "拿来" };
            File.AppendAllLines(filePath, list, Encoding.UTF8);

            Console.ReadKey();
        }
    }
}

运行后:

C# 文件操作(复制、移动、重命名、创建、打开、删除)

四、读取文件

读取文件可以使用下面方式:

1.File.ReadAllText(FilePath)
2.File.ReadAllText(FilePath, Encoding) ----指定编码
3.File.ReadAllLines(FilePath)
4.File.ReadAllLines(FilePath, Encoding) ----指定编码

以字符串接收方式

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 文件操作
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string path = @"E:\myFile.txt";
            //string content = File.ReadAllText(path);
            string content = File.ReadAllText(path,Encoding.UTF8);
            Console.WriteLine(content);
            Console.ReadKey();
        }
    }
}

以字符串数组接收的方式

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 文件操作
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string path = @"E:\myFile.txt";
            //string[] content = File.ReadAllLines(path); 
            string[] content = File.ReadAllLines(path, Encoding.UTF8);
            for (int i = 0; i < content.Length; i++)
            {
                Console.WriteLine(content[i]);
            }
            Console.ReadKey();
        }
    }
}

采用流(Stream)的方式来读取内容

1.StreamReader(FilePath)
2.StreamReader(FilePath, Encoding)
3.StreamReader(FileStream)
4.StreamReader(FileStream, Encoding)
5.File.OpenText(FilePath)
6.FileInfo.OpenText()

基于StreamReader,一行一行读取

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 文件操作
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string path = @"E:\myFile.txt";
            //StreamReader sr1 = new StreamReader(path); 
            //StreamReader sr2 = new StreamReader(path, Encoding.UTF8);
            

            //初始化FileStream
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None); 
            //StreamReader sr3 = new StreamReader(fs); 
            StreamReader sr4 = new StreamReader(fs, Encoding.UTF8);

            string line = string.Empty;
            while((line = sr4.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
            sr4.Close();
            
            Console.ReadKey();
        }
    }
}

一次性读完

string path = @"E:\myFile.txt";
StreamReader sr = new StreamReader(path, Encoding.UTF8);
string content = sr.ReadToEnd();
Console.WriteLine(content);
sr.Close();

五、复制文件

要复制文件,可以使用System.IO.File.Copy()方法。该方法接受源文件路径和目标文件路径作为参数,并将源文件复制到目标文件。如果目标文件已存在,则将被覆盖。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 文件操作
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string sourceFilePath = @"E:\myFile.txt";
            string destinationFilePath = @"E:\myFile_copy.txt";
            File.Copy(sourceFilePath, destinationFilePath);

            Console.ReadKey();
        }
    }
}

打开对应的目录,可以看到拷贝成功了,而且字节数也是一样的

C# 文件操作(复制、移动、重命名、创建、打开、删除)

六、移动文件

要移动文件,可以使用System.IO.File.Move()方法。该方法接受源文件路径和目标文件路径作为参数,并将源文件移动到目标文件。如果目标文件已存在,则将被覆盖。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 文件操作
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string sourceFilePath = @"E:\myFile.txt";
            string destinationFilePath = @"D:\myFile.txt";
            File.Move(sourceFilePath, destinationFilePath);

            Console.ReadKey();
        }
    }
}

七、重命名文件

要重命名文件,可以使用System.IO.File.Move()方法。该方法接受源文件路径和目标文件路径作为参数,并将源文件重命名为目标文件。如果目标文件已存在,则将被覆盖。

在上一节 移动文件 中,我们将 myFile.txt 文件移动到 D 盘了,执行下面操作之前,要先剪切回来再执行操作哦

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 文件操作
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string filePath = @"E:\myFile.txt";
            string newFilePath = @"E:\myFile_new.txt";
            File.Move(filePath, newFilePath);

            Console.ReadKey();
        }
    }
}

运行后,可以看到效果了

C# 文件操作(复制、移动、重命名、创建、打开、删除)

 C# 文件操作(复制、移动、重命名、创建、打开、删除)

八、删除文件

要删除文件,可以使用System.IO.File.Delete()方法。该方法接受文件路径作为参数,并将该文件从磁盘上删除。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 文件操作
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string newFilePath = @"E:\myFile_new.txt";
            File.Delete(newFilePath);

            Console.ReadKey();
        }
    }
}

结束

如果这个帖子对你有所帮助,欢迎 关注 + 点赞 + 留言

end文章来源地址https://www.toymoban.com/news/detail-429892.html

到了这里,关于C# 文件操作(复制、移动、重命名、创建、打开、删除)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 解决打开文件、文件夹、拖拽复制删除时鼠标卡顿

    最近新换了电脑,一开始没有问题,但是用了一段时间后又出现了鼠标卡顿(说明这问题不是因为电脑性能太差),最后参考如下文章解决问题【学习笔记】记录一个win 11 操作文件卡顿,Windows 资源管理器CPU占用飙升问题_shexview-x64-CSDN博客 原来是百度网盘惹的祸 我这个方法

    2024年02月11日
    浏览(77)
  • 删除、移动、复制文件时总是要卡在99%一段时间解决方法

    Win10文件夹重命名、移动、删除等操作卡顿3-5秒。 原因分析: 查看发现,卡顿期间资源管理器无响应,并且其高度占用CPU资源,但是对于非文件夹文件操作没有问题。 解决方案: 1、双击“此电脑”,选择“查看”,再选择“选项”; 2、依次选择“常规”–“清除”–“还原

    2024年02月10日
    浏览(35)
  • Linux对文件夹操作(复制,移动)

    将vue 文件夹下面的所有文件,复制到同目录下vue-copy文件夹下面 -a:相当于 -d、-p、-r 选项的集合,这几个选项我们一一介绍; -d:如果源文件为软链接(对硬链接无效),则复制出的目标文件也为软链接; -i:询问,如果目标文件已经存在,则会询问是否覆盖; -l:把目标文

    2024年02月15日
    浏览(36)
  • Python 文件处理指南:打开、读取、写入、追加、创建和删除文件

    文件处理是任何Web应用程序的重要部分。Python有多个用于创建、读取、更新和删除文件的函数。 在Python中处理文件的关键函数是open()函数。open()函数接受两个参数:文件名和模式。 有四种不同的方法(模式)可以打开文件: \\\"r\\\" - 读取 - 默认值。打开一个文件以进行读取,如

    2024年02月05日
    浏览(52)
  • C#怎样创建、移动及遍历文件夹

    一、使用DirectoryInfo类创建文件夹: 1、使用DirectoryInfo前需要引入命名空间: 2、DirectoryInfo类没有静态方法,仅可以用于实例化的对象,  3、判断输入的文件夹名称是否为空,弹出提示框 4、 通过Exists()方法判断要创建的文件夹是否存在 5、创建文件夹:  二、使用DirectoryI

    2024年02月12日
    浏览(29)
  • c# 操作剪切板,复制文本或文件

     1.将文本内容放入剪切板          Clipboard.SetDataObject(\\\"要复制的内容\\\");//复制内容到粘贴板 2.将文本内容从剪切板取出               IDataObject iData = Clipboard.GetDataObject();           if (iData.GetDataPresent(DataFormats.Text))            {            label1.Text = (String)iData.GetData(D

    2023年04月08日
    浏览(29)
  • Android文件基本操作(创建文件(夹)、复制文件(夹)、设置文件访问权限)

    将src目录下的info.txt复制到dst目录并重命名为info_dst.txt 1、 方法一:调用java.nio.file.Files.copy() 2、方法二:使用输入输出流 1、删除文件 只需要调用File的delete方法即可删除指定文件 2、删除文件夹 如果文件夹不为空,调用delete方法是无法删除文件夹的。需要先删除文件夹中包含

    2024年02月01日
    浏览(76)
  • 空文件夹删不掉打不开,“该项目不存在请确认该项目位置“,“项目正在打开中无法删除“,“文件已损坏或者已经被移动删除“(多种方法图文详解,细节需要注意,以及可能遇到的问题)

    这个删不掉的文件或文件夹其实是Windows系统的祖传bug到目前为止依然没有修复,所以说我们需要通过特别的手段来处理它,听我慢慢讲他的缘由可能会对解决这个问题的帮助更多,会有几种方法,我都试过了的,我把最后一种成功的放在第一个讲,没有成功的可以参考。 事情缘由因

    2024年02月06日
    浏览(60)
  • Linux | 创建 | 删除 | 查看 | 基本命名详解

    本门课程学习Linux系统编程,你可能要问Linux从哪里来?它是怎么发展的?在这里简要介绍Linux的发展史。要说Linux,还得从UNIX说起。 下面内容来自维基百科 Linux是一种自由和开放源码的类UNIX操作系统。该操作系统的内核由林纳斯·托瓦兹在1991年10月5日首次发布,再加上用户

    2024年02月05日
    浏览(25)
  • 初识Unity——创建代码、场景以及五个常用面板(创建C#代码、打开代码文件、场景的创建、Project、Hierarchy、Inspector、Scene、Game )

    目录 创建代码 创建C#脚本 打开代码文件 可能出现的问题 场景 场景的创建 基本介绍 五个窗口面板的作用 Project Hierarchy Inspector Scene Game  从unity2018版本开始,unity就开始不再维护和推荐JavaScript for Unity以及Boo等语言,现在官方主推和最常用的脚本语言是C#。 创建一个脚本之后

    2024年02月07日
    浏览(35)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包