C#读取和写入txt文档(在unity中示例)

本篇内容简单介绍如何在c#中内容读取和写入txt文档

注意:先在Unity的StreamingAssets文件夹中创建一个txt文档

一、读取txt

1.1全部一起读取

cs 复制代码
private void ReadText01()
{
    string filePath = Path.Combine(Application.streamingAssetsPath, "testTXT.txt");
    // 读取文件内容
    if (File.Exists(filePath))
    {
        string fileContent = File.ReadAllText(filePath);
        Debug.Log(fileContent); // 输出文件内容
    }
    else
    {
        Debug.LogError("文件不存在: " + filePath);
    }
}

1.2全部逐行读取

cs 复制代码
private void ReadText02()//逐行读取
{
    string filePath2 = Path.Combine(Application.streamingAssetsPath, "testTXT.txt");
    // 读取文件内容
    if (File.Exists(filePath2))
    {
        using (StreamReader reader = new StreamReader(filePath2))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                Debug.Log(line); // 输出每一行内容
            }
        }
    }
    else
    {
        Debug.LogError("文件不存在: " + filePath2);
    }
}

二、写入txt

2.1全部一起写入(删除旧内容,添加新内容)

cs 复制代码
 private void WriteTxt01()//全部写入
 {
     string filePath3 = Path.Combine(Application.streamingAssetsPath, "testTXT.txt");
     // 要写入的内容
     string contentToWrite = "方法1小文件写入txt";
     // 写入文件内容
     File.WriteAllText(filePath3, contentToWrite);
 }

2.2全部逐行写入(删除旧内容,添加新内容)

cs 复制代码
private void WriteTxt02()//逐行写入
{
    string filePath4 = Path.Combine(Application.streamingAssetsPath, "testTXT.txt");
    // 要写入的内容
    string contentToWrite2 = "Hello, this is a test message.\nThis is a new line.";
    // 使用 StreamWriter 写入文件内容
    using (StreamWriter writer = new StreamWriter(filePath4))
    {
        writer.WriteLine(contentToWrite2); // 写入内容
    }
}

2.3全部一起写入(不删除旧内容情况下直接添加新内容)

cs 复制代码
private void WriteTxt01()//全部写入
{
    string filePath3 = Path.Combine(Application.streamingAssetsPath, "testTXT.txt");
    // 要写入的内容
    string contentToWrite = "方法1小文件写入txt";
    // 追加文件内容
    File.AppendAllText(filePath3, contentToWrite);
}

2.4全部逐行写入(不删除旧内容情况下直接添加新内容)

cs 复制代码
private void WriteTxt02()//支持逐行写入
{
    // 设置文本文件的路径(在 Unity 的 StreamingAssets 文件夹中)
    string filePath4 = Path.Combine(Application.streamingAssetsPath, "testTXT.txt");

    // 要写入的内容
    string contentToWrite2 = "Hello, this is a test message.\nThis is a new line.";
    using (StreamWriter writer2 = new StreamWriter(filePath4, true))
    {
        writer2.WriteLine("This line will be appended.");
    }
}
相关推荐
dzj20212 小时前
Unity是如何把3D场景显示到屏幕上的——Unity的渲染过程
3d·unity·游戏引擎·渲染·图形学
中游鱼8 小时前
如何序列化和反序列化动态 XmlElement ?
windows·microsoft·c#
唐青枫15 小时前
C#.NET dapper 详解
c#·.net
死也不注释18 小时前
【鸡零狗碎记录】
unity·c#
Maybe_ch18 小时前
.NET-键控服务依赖注入
开发语言·c#·.net
★YUI★21 小时前
学习游戏制作记录(剑投掷技能)7.26
学习·游戏·unity·c#
小乖兽技术21 小时前
C#与C++交互开发系列(二十四):WinForms 应用中嵌入C++ 原生窗体
c++·c#·交互
I'mSQL1 天前
C#与WPF使用mvvm简单案例点击按钮触发弹窗
开发语言·c#·wpf
工藤新一OL1 天前
把xml的格式从utf-8-bom转为utf-8
xml·c#·asp.net·.netcore·visual studio
henreash1 天前
NLua和C#交互
开发语言·c#·交互