【问题标题】:How to save a file from a windows store app in Unity如何在 Unity 中保存 Windows 商店应用程序中的文件
【发布时间】:2015-09-25 15:01:04
【问题描述】:

我正在 Unity3D 中制作一个应用程序,以便在 Windows 商店中发布。 您似乎无法使用 .net streamwriter 写入文件。 我想将 csv 文件保存到某个位置,然后使用 WWW 类将其发送到服务器。 我找到了一个从 assets 文件夹中读取文件的项目。 这是那个的代码......

using UnityEngine;
using System;
using System.Collections;
using System.IO;
#if NETFX_CORE
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Streams;
#endif
namespace IOS
{
    public class File
    {
        public static object result;
#if NETFX_CORE
        public static async Task<byte[]> _ReadAllBytes(string path)
        {
            StorageFile file = await StorageFile.GetFileFromPathAsync(path.Replace("/", "\\"));
            byte[] fileBytes = null;
            using (IRandomAccessStreamWithContentType stream = await file.OpenReadAsync())
            {
                fileBytes = new byte[stream.Size];
                using (DataReader reader = new DataReader(stream))
                {
                    await reader.LoadAsync((uint)stream.Size);
                    reader.ReadBytes(fileBytes);
                }
            }
            return fileBytes;
        }
#endif


        public static IEnumerator ReadAllText(string path)
        {
#if NETFX_CORE
            Task<byte[]> task = _ReadAllBytes(path);
            while (!task.IsCompleted)
            {
                yield return null;
            }
            UTF8Encoding enc = new UTF8Encoding();
            result = enc.GetString(task.Result, 0, task.Result.Length);
#else
            yield return null;
            result = System.IO.File.ReadAllText(path);
#endif
        }
    }

}

public class Example : MonoBehaviour
{

    private string data;

    IEnumerator ReadFile(string path)
    {
        yield return StartCoroutine(IOS.File.ReadAllText(path));
        data = IOS.File.result as string;

    }

    public void OnGUI()
    {
        string path = Path.Combine(Application.dataPath, "StreamingAssets/Data.txt");
        if (GUILayout.Button("Read file '" + path + "'"))
        {
            StartCoroutine(ReadFile(path));
        }
        GUILayout.Label(data == null ? "<NoData>" : data);
    }
}

这里是使用 Windows 应用商店应用序列化的 MSDN 文档

https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh758325.aspx

我想知道如何调整它以适应我的目的。 IE。将文件写入特定位置,以便稍后通过 WWW 发送文件时引用。

【问题讨论】:

    标签: serialization unity3d windows-store


    【解决方案1】:

    主要问题是位置。 Application.dataPath 是应用程序包中的只读数据。要写入数据,请使用Application.persistentDataPath 在应用程序数据文件夹中获取可写位置。

    Unity 通过其UnityEngine.Windows.File 对象提供 System.IO.File 的替代方案。您可以在 System.IO 和 UnityEngine.Windows 之间切换使用,然后调用 File.ReadAllBytes 或 File.WriteAllBytes,无论平台如何。

    这基本上就是您的代码片段正在做的事情,除了 Unity 已经提供了它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-18
      • 2012-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多