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 <<<");
}
如何我可以避免在文件中写入空条目/删除数据吗?
没有重新启动我的代码没有触发 –
其实我的问题是文件越来越writted,而不是原始字符串空白区正在写(对不起,我的英文不好) –
如果是这样的话,那么你需要扩大你的故障排除,并检查objectToWrite是否有你期望的结构。此外,您需要验证JsonConvert.SerializeObject是否按照您所期望的那样进行序列化。 –