[英]StreamWriter generates 0 byte file
我有以下逻辑,这些逻辑通过计时器每20分钟调用一次,它将对象的内容序列化为文件路径,我看到的filePath是\\ hard disk \\ logs \\ applicationstate.xml,请注意,我确认这是有效路径
它在大多数时间都有效,但是this.StreamWriter = new StreamWriter(filePath);
在this.StreamWriter = new StreamWriter(filePath);
行上获得System.IO.IOeException
this.StreamWriter = new StreamWriter(filePath);
具有以下堆栈堆栈跟踪:
位于System.IO .__ Error.WinIOError(Int32 errorCode,String str)\\ r \\ n位于System.IO.FileStream..ctor(字符串路径,FileMode模式,FileAccess访问,FileShare共享,Int32 bufferSize,布尔useAsync,字符串msgPath) \\ r \\ n在System.IO.FileStream..ctor(字符串路径,FileMode模式,FileAccess访问,FileShare共享,Int32 bufferSize)\\ r \\ n在System.IO.StreamWriter.CreateFile(字符串路径,布尔值附加)\\ r \\ n
在System.IO.StreamWriter..ctor(字符串路径,布尔值附加,编码编码,Int32缓冲区大小)\\ r \\ n在System.IO.StreamWriter..ctor(字符串路径)\\ r \\ n在Shs.ScanPanel.CA。 DataManager.DataManagercr.CopyData(对象数据)\\ r \\ n
在System.Threading.Timer.ring()\\ r \\ n“
发生这种情况时,我看到\\ hard disk \\ logs \\ applicationstate.xml存在,但它有0个字节。
所以我的问题是,StreamWriter会导致该0字节文件首先生成吗? 我在MSDN上的StreamWriter下阅读了IOException,它指出以下内容
IOException
路径包含文件名,目录名或卷标签语法的语法错误或无效。
这让我感到困惑,是因为它试图将流写入器打开为0字节文件吗? 这个0字节是否可以在该代码最后一次运行的位置(将空对象序列化到文件中)生成? 如果是这样,为什么我没有在Visual Studio中看到该异常?
if (filePath != string.Empty)
{
if (this.StateObject == null)
{
this.StateObject = new State();
}
//Do something to my StateObject object
this.StreamWriter = new StreamWriter(filePath);
this.Serializer = new XmlSerializer(typeof(State));
this.Serializer.Serialize(this.StreamWriter, this.StateObject);
}
else
{
if (this.log != null)
{
this.log.Write(LogLevel.Error, this.componentName, "CopyData : Unable to initilize State Object");
}
}
}
else
{
if (this.log != null)
{
this.log.Write(LogLevel.Error, this.componentName, "CopyData : Error while retrieving Current working directory");
}
}
}
catch (Exception ex)
{
if (this.log != null)
{
this.log.Write(ex, this.componentName);
}
}
finally
{
if (this.StreamWriter != null)
{
this.StreamWriter.Close();
}
}
我建议使用this.StreamWriter.Flush()以确保所有内容均已写入。
但是,您似乎异常在抱怨路径不正确。
编辑:我错过了WinCE标签
因此,我编写了一个小程序,并确认使文件具有0字节的行在this.StreamWriter = new StreamWriter(filePath);处正确。
但是真正令我困惑的是,它成功清除了文件,以便可以将新数据序列化到其中,但是同时会引发异常。 我在想这是StreamWriter api的下层,或者可能与闪存驱动器有关。...毕竟我是在WINDOW CE上运行该程序的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.