簡體   English   中英

在c#和Unity中創建和寫入txt文件時,它只會創建它,而不使用它

[英]When creating and writing a txt file in c# and Unity, it only creates it and do not use it

我正在使用c#作為主要編程語言在Unity中進行游戲。 我嘗試創建一個新的save.txt和autosave.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);



}

我不知道我做錯了什么。 PS統一運行時,如果有幫助,它表示“ IOException:在路徑C:* \\ Assets \\ Save.txt上共享沖突”

File.CreateText返回一個StreamWriter對象。 由於您沒有使用此對象(或在創建文件的新編寫器之前未將其處置),因此會拋出異常,因為多個對象具有/想要對該文件的寫訪問權限。

請了解有關IDisposable和“ using”語句的更多信息。

代替創建新的StreamWriter,嘗試使用File.CreateText()返回的StreamWriter。

雖然來自@ b00n和@martennis的答案對他們都有一定的道理,但它們還是有點不足。 一旦StreamWriter對象創建了文件,僅關閉流就無法解除它對該文件的鎖定。 因此,當您創建一個新的StreamWriter來訪問該文件時,它會引發IOException,因為您的新流仍被舊流鎖定,因此無法獲取訪問權限。 關閉流並進行處理將確保該流可以進行所需的適當清理,以釋放文件以供后續讀取。 我強烈建議您閱讀MSDN上的File API文檔,以更好地了解其功能以及如何使用它。

編輯:一種確保清除StreamWriter對象的方法是將using語句用作@O。 馬太提到。 這將遵循以下內容:

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-finally,在finally語句中調用writer.Dispose()以確保即使發生異常也已正確清理了所使用的資源。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM