2016-05-19 287 views
0

我使用StreamWriter在會話轉換中寫入文件,如登錄和註銷。重新啓動時StreamWriter數據丟失

但是,如果發生了重新啓動只是當我們寫/關閉文件,我們得到了一個空文件,並在它被越來越刪除 已經有一段時間數據的時間這是我的代碼

public void ToJson(T objectToWrite) 
     { 
      InformFileLogger.Instance.Debug(">>> start >>>"); 
      try 
      { 
       string json = null; 
       string directory = Path.GetDirectoryName(this.serializeFilePath); 
       if (!Directory.Exists(directory)) 
       { 
        Directory.CreateDirectory(directory); 
       } 

       if (File.Exists(this.serializeFilePath)) 
       { 
        if (new FileInfo(this.serializeFilePath).Length == 0) 
        { 
         File.Delete(this.serializeFilePath); 
        } 
       } 

       json = JsonConvert.SerializeObject(objectToWrite); 

       if (json != null) 
       { 
        using (StreamWriter streamWriter = new StreamWriter(this.serializeFilePath)) 
        { 
         streamWriter.WriteLine(json); 
         streamWriter.Close(); 
        } 
       } 
      } 
      catch (Exception ex) 
      { 
       InformEventLogger.Error(ex.ToString()); 
       InformFileLogger.Instance.Error(InformHelper.ExceptionMessageFormat(ex)); 
      } 

      InformFileLogger.Instance.Debug("<<< end <<<"); 
     } 

如何我可以避免在文件中寫入空條目/刪除數據嗎?

回答

0

這實際上取決於重啓的觸發方式。

除非重啓您的代碼觸發,你將不能夠確保您的代碼可以在重新啓動前做任何事情 - 包括完成一個StreamWriter功能。

+0

沒有重新啓動我的代碼沒有觸發 –

+0

其實我的問題是文件越來越writted,而不是原始字符串空白區正在寫(對不起,我的英文不好) –

+1

如果是這樣的話,那麼你需要擴大你的故障排除,並檢查objectToWrite是否有你期望的結構。此外,您需要驗證JsonConvert.SerializeObject是否按照您所期望的那樣進行序列化。 –

相關問題