如何从Unity中的Windows应用商店应用程序保存文件

时间:2015-09-25 15:01:05

标签: serialization unity3d windows-store

我正在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

我想知道如何根据我的目的调整它。即。将文件写入特定位置,以后我通过WWW发送文件时可以参考。

1 个答案:

答案 0 :(得分:2)

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

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

这基本上是你的代码snippit正在做的事情,除了Unity已经提供它。