You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Unity项目中用C#保存现有文本文件

在Unity C#中保存已有文本文件(无内容修改)

首先明确:如果文本文件本身没有内容修改,单纯的“保存”在文件系统层面没有实质作用——文件已经处于最新状态。但如果你的需求是标记文件已被处理(更新修改时间),或者强制操作系统将文件缓存同步到磁盘,可以用以下两种实现方式:

方法1:更新文件最后写入时间

适合需要让系统或其他程序感知文件已被“保存”标记的场景:

using System.IO;
using UnityEngine;

public class FileSaver : MonoBehaviour
{
    public void MarkFileAsSaved(string filePath)
    {
        if (File.Exists(filePath))
        {
            // 将文件最后写入时间设为当前时间
            File.SetLastWriteTime(filePath, System.DateTime.Now);
            Debug.Log("文件已标记为保存:" + filePath);
        }
        else
        {
            Debug.LogError("目标文件不存在:" + filePath);
        }
    }
}

方法2:强制同步文件缓存到磁盘

如果文件之前有过写入操作,想确保内存中的缓存数据完全写入磁盘(避免意外断电丢失),可以用此方法:

using System.IO;
using UnityEngine;

public class FileSaver : MonoBehaviour
{
    public void SyncFileToDisk(string filePath)
    {
        if (File.Exists(filePath))
        {
            // 以读写模式打开文件,确保能触发缓存同步
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                // true参数表示强制将缓存写入磁盘
                fs.Flush(true);
                Debug.Log("文件缓存已同步到磁盘:" + filePath);
            }
        }
        else
        {
            Debug.LogError("目标文件不存在:" + filePath);
        }
    }
}

实用提示

  • 在Unity中操作文件时,优先使用Application.persistentDataPath作为根路径,避免权限问题:
    string targetFilePath = Path.Combine(Application.persistentDataPath, "yourTextFile.txt");
    
  • 移动端(iOS/Android)有严格的文件权限限制,确保操作的文件位于允许访问的目录内。

内容的提问来源于stack exchange,提问作者Asmar Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 16:40:35