2016-05-07 64 views
0

我已經使用以下代碼進行文件讀取和寫入。iOS中的文件讀寫錯誤

private void StorePuzzleData() 
{ 
    FileInfo fileInfo = new FileInfo (Application.persistentDataPath + "\\" + difficultyLevel + puzzleId + ".txt"); 

    if (fileInfo.Exists) 
     fileInfo.Delete(); 

    string fileData = string.Empty; 

    foreach (CellInformation cellInfo in cellInfoList) 
     fileData += cellInfo.RowIndex + "#" + cellInfo.ColIndex + "#" + cellInfo.number + "#" + cellInfo.CellColor + "#" + cellInfo.CellDisplayColor + "#" + (cellInfo.IsGroupComplete ? 1 : 0) + ","; 

    StreamWriter streamWriter = fileInfo.CreateText(); 
    streamWriter.WriteLine (fileData); 
    streamWriter.Close(); 

    DataStorage.StorePuzzleTimePassed (difficultyLevel, puzzleId, GameController.gamePlayTime); 

} 

private void ReadPuzzleData() 
{ 
    // format: rownumber, colnumber, number, cellcolor, celldisplaycolor, isgroupcomplete 

    StreamReader streamReader = File.OpenText (Application.persistentDataPath + "\\" + difficultyLevel + puzzleId + ".txt"); 
    string fileData = streamReader.ReadLine(); 
} 

但是我在實際iOS設備運行中遇到了以下錯誤。此代碼在iMac以及Android設備中正確工作。

enter image description here

enter image description here

請給我一些建議什麼樣的變化,我需要做的,使這是正確的。

+0

唯一不正確的是你的路徑中的最後一個斜槓是反斜槓,而所有其他斜槓都是正斜槓,請在代碼中的任何地方嘗試使用「//」而不是「\\」 –

+0

然後它會在Windows上崩潰:) –

回答

3

看來你在類Unix(Apple Mac OS)環境中使用Windows風格的路徑。請注意,你有喜歡

C:\Users\Maxi\Desktop 

在類Unix系統,但是像

/var/mobile/Containers 

你會發現,在錯誤的道路已混合向前和向後斜槓,這使得反斜線路徑窗口路徑無效。

/var/mobile/Containers/Data/Application/2.....\debutan1.txt 

始終生成正確路徑的正確方法是使用Path.Combine(string, string)函數。這將結合使用正確的目錄路徑分隔符的兩個路徑,也可以通過Path.DirectorySeparatorChar獨立訪問。

因此,爲了使你的代碼是正確的,你會做

using System.IO; /* must be imported */ 

private void StorePuzzleData() 
{ 
    FileInfo fileInfo = new FileInfo (Path.Combine(Application.persistentDataPath, difficultyLevel + puzzleId + ".txt")); 

    if (fileInfo.Exists) 
     fileInfo.Delete(); 

    string fileData = string.Empty; 

    foreach (CellInformation cellInfo in cellInfoList) 
     fileData += cellInfo.RowIndex + "#" + cellInfo.ColIndex + "#" + cellInfo.number + "#" + cellInfo.CellColor + "#" + cellInfo.CellDisplayColor + "#" + (cellInfo.IsGroupComplete ? 1 : 0) + ","; 

    StreamWriter streamWriter = fileInfo.CreateText(); 
    streamWriter.WriteLine (fileData); 
    streamWriter.Close(); 

    DataStorage.StorePuzzleTimePassed (difficultyLevel, puzzleId, GameController.gamePlayTime); 

} 

private void ReadPuzzleData() 
{ 
    // format: rownumber, colnumber, number, cellcolor, celldisplaycolor, isgroupcomplete 

    StreamReader streamReader = File.OpenText (Path.Combine(Application.persistentDataPath, difficultyLevel + puzzleId + ".txt")); 
    string fileData = streamReader.ReadLine(); 
} 

如果這仍然給出了一個「拒絕訪問」的錯誤一定是因爲filepermissions的。然後發佈ls -la <thatpath>的輸出。

+0

現在我正在測試用這個建議構建:http://answers.unity3d.com/questions/161526/write-to-iphone-file-system-access-denied.html – Siddharth

+0

太棒了,這工作完美... 。:) – Siddharth