2015-09-25 84 views
0

我正在Unity3D中制作应用程序,以便在Windows应用商店中发布。 看来你不能用.net streamwriter写文件。 我想将csv文件保存到某个位置,然后使用WWW类将其发送到服务器。 我找到了一个项目,从assets文件夹中读取一个文件。 为继承人的代码...如何在Unity中保存Windows应用商店中的文件

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); 
    } 
} 

继承人的MSDN文档与Windows应用商店的应用程式序列化

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

我不知道如何去适应这个适合我的目的。即。将文件写入一个特定的位置,以后我可以通过WWW发送文件时参考。

回答

1

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

Unity通过其UnityEngine.Windows.File对象提供了System.IO.File的替代方法。你可以在System.IO和UnityEngine.Windows之间切换使用,然后调用File.ReadAllBytes或File.WriteAllBytes而不管平台。

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

相关问题