首页 > 编程语言 >C# File文件处理 创建和写文件

C# File文件处理 创建和写文件

时间:2023-03-07 13:25:39浏览次数:41  
标签:文件 string C# System File using path

C# File文件处理 创建和写文件

在C# 程序开发中,我们往往会遇到很多文件上传,文件写入等对于文件的操作业务需要开发,文件处理也是任何应用程序的重要组成部分。C# 有几种创建,读取,更新和删除文件的方法。本文主要介绍C# File文件处理 创建和写文件。

 

1、使用 File.Create()创建并写入文件

要使用C# 创建文件,可以使用File.Create()FileStream()方法创建文件,例如

1)使用StreamReader

using System;
using System.IO;
using System.Text;

class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";

        try
        {
            // 创建文件,如果文件存在,则覆盖该文件。
            using (FileStream fs = File.Create(path))
            {
                byte[] info = new UTF8Encoding(true).GetBytes("https://www.cjavapy.com");
                // 向文件中写入一些信息。
                fs.Write(info, 0, info.Length);
            }

            // 打开流并读取。
            using (StreamReader sr = File.OpenText(path))
            {
                string s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    Console.WriteLine(s);
                }
            }
        }

        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
}

2)使用File.WriteAllLines

using System;
using System.IO;
using System.Text;
class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";
        // 此文本只添加一次到文件中。
        if (!File.Exists(path))
        {
            // 创建一个要写入的文件。
            string[] createText = { "Hello", "And", "Welcome" };
            File.WriteAllLines(path, createText, Encoding.UTF8);
        }
        // 此文本总是被添加,使文件随着时间的推移而变长
        string appendText = "This is extra text" + Environment.NewLine;
        File.AppendAllText(path, appendText, Encoding.UTF8);
        // 打开要从中读取的文件。
        string[] readText = File.ReadAllLines(path, Encoding.UTF8);
        foreach (string s in readText)
        {
            Console.WriteLine(s);
        }
    }
}

3)使用WriteAllText

using System;
using System.IO;
using System.Text;
class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";
        // 此文本只添加一次到文件中。
        if (!File.Exists(path))
        {
            //创建一个要写入的文件。
            string createText = "Hello and Welcome" + Environment.NewLine;
            File.WriteAllText(path, createText, Encoding.UTF8);
        }
        // 此文本总是被添加,使文件随着时间的推移而变长
        string appendText = "This is extra text" + Environment.NewLine;
        File.AppendAllText(path, appendText, Encoding.UTF8);
        // 打开要从中读取的文件。
        string readText = File.ReadAllText(path);
        Console.WriteLine(readText);
    }
}

4)使用FileStream对象的Write()方法

using System;
using System.IO;
using System.Text;
class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";
        if (!File.Exists(path))
        {
            // 创建文件
            using (FileStream fs = File.Create(path))
            {
                Byte[] info = new UTF8Encoding(true).GetBytes("https://www.cjavapy.com");
                fs.Write(info, 0, info.Length);
            }
        }
        // 打开文件并读取
        using (FileStream fs = File.OpenRead(path))
        {
            byte[] b = new byte[1024];
            UTF8Encoding temp = new UTF8Encoding(true);
            while (fs.Read(b,0,b.Length) > 0)
            {
                Console.WriteLine(temp.GetString(b));
            }
        }
    }
}

2、使用FileStream()创建并写入文件

using System;
using System.IO;
class FStream
{
    static void Main()
    {
        const string fileName = "cjavapy.dat";
        // 创建要写入文件的随机数据。
        byte[] dataArray = new byte[100000];
        new Random().NextBytes(dataArray);
        using(FileStream
            fileStream = new FileStream(fileName, FileMode.Create))
        {
            // 将数据逐字节写入文件。
            for(int i = 0; i < dataArray.Length; i++)
            {
                fileStream.WriteByte(dataArray[i]);
            }
            // 将流位置设置为文件的开头。
            fileStream.Seek(0, SeekOrigin.Begin);    
        }
    }
}

注意:文件写入时追加内容还可以使用AppendAllLinesAppendAllText

AppendText等方法。

 3、C# File和fileinfo类

两个类功能差不多,File是静态方法实现的,Fileinfo通过实例方法实现的。FileInfo使用示例如下,

using System;
using System.IO;
class Test
{
    public static void Main()
    {
        string path = Path.GetTempFileName();
        var fi1 = new FileInfo(path);
        // 创建写入文件
        using (StreamWriter sw = fi1.CreateText())
        {
            sw.WriteLine("Hello");
            sw.WriteLine("And");
            sw.WriteLine("Welcome");
        }	
        // 打开读取文件
        using (StreamReader sr = fi1.OpenText())
        {
            var s = "";
            while ((s = sr.ReadLine()) != null)
            {
                Console.WriteLine(s);
            }
        }
        try
        {
            string path2 = Path.GetTempFileName();
            var fi2 = new FileInfo(path2);
            // 确保目标不存在。
            fi2.Delete();
            // 复制文件
            fi1.CopyTo(path2);
            Console.WriteLine($"{path} was copied to {path2}.");
            // 删除创建的文件
            fi2.Delete();
            Console.WriteLine($"{path2} was successfully deleted.");
        }
        catch (Exception e)
        {
            Console.WriteLine($"The process failed: {e.ToString()}");
        }
    }
}

标签:文件,string,C#,System,File,using,path
From: https://www.cnblogs.com/GaoUpUp/p/17187776.html

相关文章

  • C# File文件处理 相关方法
    C#File文件处理相关方法在C#程序开发中,我们往往会遇到很多文件上传,文件写入等对于文件的操作业务需要开发,文件处理也是任何应用程序的重要组成部分。C#有几种......
  • C# File文件处理 删除文件
    C#File文件处理删除文件 在C#程序开发中,我们往往会遇到很多文件上传,文件写入等对于文件的操作业务需要开发,文件处理也是任何应用程序的重要组成部分。C#有......
  • C# File文件处理 读文件
    C#File文件处理读文件在C#程序开发中,我们往往会遇到很多文件上传,文件写入等对于文件的操作业务需要开发,文件处理也是任何应用程序的重要组成部分。C#有几种创......
  • .NET(C#) 中的程序集
    .NET(C#)中的程序集 程序集构成了.NET应用程序的部署、版本控制、重用、激活范围和安全权限的基本单元。程序集是为协同工作而生成的类型和资源的集合,这些......
  • C# 特性标签(Attribute)
    C#特性标签(Attribute)公共语言运行时使你能够添加类似于关键字的描述性声明(称为特性),以便批注编程元素(如类型、字段、方法和属性)。.NET出于多种原因且为解决许......
  • C# 索引器
    C#索引器 索引器(Indexer)是C#引入的一个新型的类成员,它使得类中的对象可以像数组那样方便、直观的被引用。索引器非常类似于属性,但索引器可以有参数列表,且只......
  • C# 反射(Reflection)
    C#反射(Reflection)反射提供描述程序集、模块和类型的对象(Type类型)。可以使用反射动态地创建类型的实例,将类型绑定到现有对象,或从现有对象中获取类型,然后调用......
  • C# 事件(event)
    C#事件(event) 事件是一种特殊的多播委托,仅可以从声明事件的类或结构中对其进行调用。类或对象可以通过事件向其他类或对象通知发生的相关事情。发送(或引发)事......
  • C# 委托(delegate)
    C#委托(delegate)委托是一个类,它定义了方法的类型,使得可以将方法当作另一个方法的参数来进行传递,这种将方法动态地赋给参数的做法,可以避免在程序中大量使用If-El......
  • RocketMQ高可用机制
    RocketMQ高可用机制集群部署模式1.单master模式2.多master模式配置配置文件broker.properties的brokerClusterName需要保持一致brokerId需要为0,0代表为0优缺点......