C# 文件操作

文章目录

C# 文件操作

创建文件

csharp 复制代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Test
    {
        int result;
        Test()
        {
            result = 0;
        }
        public void division(int num1,int num2)
        {
            try
            {
                result = num1 / num2;
            }
            catch(DivideByZeroException e)
            {
                Console.WriteLine("Exception caught:{0}", e);
            }
            finally
            {
                Console.WriteLine("Result:{0}", result);
            }
        }
        static void Main(string[] args)
        {
            try
            {
                string filePath = @"E:\File.txt";
                FileStream fileStream = File.Create(filePath);
                fileStream.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("文件创建失败:" + e.Message);
            }
            Console.WriteLine("文件创建成功");
            Console.ReadLine();
        }
    }

}

运行结果

写入文件

写入文件可以使用下面方式:

  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 方法时,如果指定的文件路径不存在,会创建一个新文件;如果文件已经存在,则会覆盖原文件。

程序文件

csharp 复制代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Test
    {
        int result;
        Test()
        {
            result = 0;
        }
        static void Main(string[] args)
        {
            string filePath = @"E:\File.txt";
            string content = "记事本记事本记事本";
            File.WriteAllText(filePath, content, Encoding.UTF8);
            Console.ReadLine();
        }
    }

}

运行结果

WriteAllLines-写入多行

csharp 复制代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Test
    {
        static void Main(string[] args)
        {
            string filePath = @"E:\File.txt";
            //string content = "记事本记事本记事本";
            string[] contentStr = { "aaaaaaa", "bbbbbbbbbb" };
            File.WriteAllLines(filePath, contentStr, Encoding.UTF8);
            Console.ReadLine();
        }
    }

}

运行结果

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

追加字符串

第一次执行:

运行结果

字符串追加成功:

如果要换行,就加上\n即可:

追加成功:

追加多行字符串

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

追加在后面了:

读取文件

ReadAllText

csharp 复制代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Test
    {
        static void Main(string[] args)
        {
            string filePath = @"E:\File.txt";
            string content = File.ReadAllText(filePath, Encoding.UTF8);
            Console.WriteLine(content);
            Console.ReadLine();
        }
    }
}
运行结果

ReadAllLines-用数组接收读取的内容

csharp 复制代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Test
    {
        static void Main(string[] args)
        {
            string filePath = @"E:\File.txt";
            //string content = File.ReadAllText(filePath, Encoding.UTF8);
            string[] content = File.ReadAllLines(filePath, Encoding.UTF8);
            for (int i = 0; i < content.Length; i++)
            {
                Console.WriteLine(content[i]);
            }
            Console.ReadLine();
        }
    }
}
运行结果

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

1.StreamReader(FilePath)

2.StreamReader(FilePath, Encoding)

3.StreamReader(FileStream)

4.StreamReader(FileStream, Encoding)

5.File.OpenText(FilePath)

6.FileInfo.OpenText()

基于StreamReader,一行一行读取

csharp 复制代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Test
    {
        static void Main(string[] args)
        {
            string filePath = @"E:\File.txt";
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None);
            StreamReader sr4 = new StreamReader(fs, Encoding.UTF8);
            string line = string.Empty;
            while ((line = sr4.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
            sr4.Close();
            Console.ReadLine();
        }
    }
}
运行结果

复制文件

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

csharp 复制代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Test
    {
        static void Main(string[] args)
        {
            string sourceFilePath = @"E:\File.txt";
            string destinationFilePath = @"E:\File_copy.txt";
            File.Copy(sourceFilePath, destinationFilePath);
            Console.ReadKey();
        }
    }
}

运行结果

移动文件

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

csharp 复制代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Test
    {
        static void Main(string[] args)
        {
            string sourceFilePath = @"E:\File.txt";
            string destinationFilePath = @"D:\File.txt";
            File.Move(sourceFilePath, destinationFilePath);
            Console.ReadKey();
        }
    }
}

运行结果

删除文件

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

csharp 复制代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Test
    {
        static void Main(string[] args)
        {
            string filePath = @"D:\File.txt";
            File.Delete(filePath);
            Console.ReadKey();
        }
    }
}

运行结果

文件被成功删除:

相关推荐
wrq1476 小时前
MyAccess 完整使用手册
c#·orm框架
z落落10 小时前
C# WinForm 自定义控件
开发语言·c#
lzhdim12 小时前
20260714 - 个人小作品更新
c#·notenet
小堂子这厢有礼了14 小时前
Chet.QuartzNet.UI v2.3.0 大更新!表格重构 + 系统配置 + 分析页全面升级!
前端·后端·ui·重构·c#·vue
asdzx671 天前
使用 Python 精准操控 Word 字体:获取与替换方案
python·c#·word
逝水无殇1 天前
C# 特性详解
开发语言·后端·c#
LongtengGensSupreme1 天前
C#图像内存高速拷贝:使用Marshal.AllocHGlobal与ArrayPool实现内存拷贝的几个方法
开发语言·数码相机·c#
影寂ldy1 天前
C# 五大加密算法全套实战(AES/DES对称、RSA非对称、MD5/SHA256哈希)
开发语言·c#·哈希算法
互联网底层民工1 天前
异步 / 多线程并发(高频八股 · 详解版)
c#
逝水无殇1 天前
C# 反射详解
开发语言·后端·c#