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.");
    }
}
相关推荐
HH牛码2 小时前
C# 中 Array、ArrayList 和 List 的比较
开发语言·c#
HH牛码2 小时前
C#学生管理系统 进阶(通过接口,继承接口的类,实现接口约束_对List中存储的数据进行排列)
c#
吾与谁归in3 小时前
C#实现本地Deepseek模型及其他模型的对话
人工智能·c#·wpf·deepseek
子蛟7 小时前
Get a free SSL certificate interface.
c#·ssl
一只蜗牛儿11 小时前
C# 版 OpenCV:OpenCVSharp 最详细最全面教程(万字详细总结)
开发语言·opencv·c#
学海无涯,行者无疆11 小时前
使用Jenkins实现Windows服务器下C#应用程序发布
windows·c#·jenkins·.net·cicd·自动发布·一键发布
tnnnnt13 小时前
今天锐评一下C#
开发语言·c#
Sator114 小时前
C#与AI的交互(以DeepSeek为例)
ai·语言模型·c#
玩c#的小杜同学16 小时前
从“Switch-case“到“智能模式“:C#模式匹配的终极进化指南
开发语言·前端·c#·.net
步、步、为营18 小时前
解锁C# XML编程:从新手到实战高手的蜕变之路
xml·数据库·c#