2017-06-14 18 views
-1

我使用c#作爲主要編程語言在Unity中製作遊戲。如果它不存在於應用程序文件夾中,我嘗試創建一個新的save.txt和autosave.txt。它可以創建它,但它不能正常工作。這裏是我的代碼: 創建並寫入新的保存:在c#和Unity中創建和編寫txt文件時,它只創建它並且不使用它

void Start() { 
    if(!File.Exists(Application.dataPath.ToString() + "/Save.txt")) 
    { 
     File.CreateText(Application.dataPath.ToString() + @"/Save.txt"); 
     saveFilePath = Application.dataPath.ToString() + @"/Save.txt"; 

     TextWriter writer = new StreamWriter(saveFilePath, false); 
     writer.WriteLine("10:21:59", "13/06/2017", "1", "1", "-21", "20000", "100", "500", "50", "20", "500","2","1","1","5000", "10"); 
     writer.Close(); 

    } 
    if(!File.Exists(Application.dataPath.ToString() + "/AutoSave.txt")) 
    { 
     File.CreateText(Application.dataPath.ToString() + @"/Autosave.txt"); 
     saveFilePath = Application.dataPath.ToString() + @"/Autosave.txt"; 

     TextWriter writer = new StreamWriter(saveFilePath, false); 
     writer.WriteLine("00:00:00", "01/01/2017", "1", "1", "-21", "20000", "100", "500", "50", "20", "500", "2", "1", "1", "5000", "10"); 
     writer.Close(); 
    } 
} 

這是我寫的存在的.txt代碼:

public void OnSaveGame() 
{ 
    saveFilePath = Application.dataPath.ToString() + @"/Save.txt"; 
    isNewGame = false; 

    TextWriter writer = new StreamWriter(saveFilePath, false); 
    theTime = System.DateTime.Now.ToString("hh:mm:ss"); theDate = System.DateTime.Now.ToString("dd/MM/yyyy"); 
    string ZeroPart = theTime + "," + theDate + ","; 
    string FirstPart = income; 
    writer.WriteLine(ZeroPart + FirstPart); 
    writer.Close(); 

    SavingPanel.SetActive(true); 
    Invoke("WaitTime",2); 



} 

我不知道我做錯了。 P.S.統一時,如果它有幫助,當我運行它時,它說它「IOException:在路徑C上共享衝突:* \ Assets \ Save.txt」

回答

0

雖然@ b00n和@martennis的答案都對他們有一定的道理,但他們有點欠缺。一旦StreamWriter對象創建文件,僅關閉流將不會緩解它在該文件上的鎖定。因此,當您創建新的StreamWriter來訪問該文件時,它會拋出IOException,因爲您的新流無法獲取訪問權限,因爲它仍然被舊的鎖定。關閉流並進行處理將確保流可以執行所需的正確清理,以便爲隨後的讀取操作釋放文件。我強烈建議在MSDN上閱讀文檔API文檔以更好地瞭解它的功能以及如何使用它。

編輯:一種確保清理StreamWriter對象的方法是使用@語句作爲使用語句。 Matei提到。這將是沿着以下線的東西:

using(TextWriter writer = new StreamWriter(saveFilePath, false)) 
{ 
    theTime = System.DateTime.Now.ToString("hh:mm:ss"); theDate = System.DateTime.Now.ToString("dd/MM/yyyy"); 
    string ZeroPart = theTime + "," + theDate + ","; 
    string FirstPart = income; 
    writer.WriteLine(ZeroPart + FirstPart); 
    writer.Close(); 
} 

using語句基本上等同於一個try-catch-最後用writer.Dispose()被調用的finally語句,以確保即使一個異常發生了所使用的資源已經得到適當清理的情況。

2

File.CreateText返回一個StreamWriter對象。由於您沒有使用該對象(或者在創建新的寫入器之前未對其進行處理),因爲多個對象具有/想要對該文件進行寫入訪問,所以會引發異常。

請詳細瞭解IDisposable和'using'語句。

1

而不是創建一個新的StreamWriter,嘗試使用由File.CreateText()返回的StreamWriter。

相關問題