2017-03-16 275 views
2

我有每分钟写入文件的应用程序。有时(每10分钟+ - )我得到错误c#“磁盘空间不足”实际上有

没有足够的空间在磁盘上

我的应用程序是一个Windows窗体应用程序。我在google上阅读了很多文章,但是它并没有给我提供任何解决方法。

例外:

抛出异常: 'System.IO.IOException' 在mscorlib.dll

我的代码:

try 
{ 
    FileStream stream = new FileStream(file, FileMode.CreateNew); 
    FileStream stream2 = new FileStream(file2, FileMode.CreateNew); 
    BinaryFormatter writer = new BinaryFormatter(); 

    writer.Serialize(stream, GetProducts().Take(80000).ToList()); 
    writer.Serialize(stream2, GetProducts().Skip(80000).ToList()); 
    stream.Flush(); 
    stream.Close(); 
    stream2.Flush(); 
    stream2.Close(); 
} 
catch(Exception ex) 
{ 
    Debug.WriteLine($"FAIL to write: {i} - {ex.Message}"); 
} 

在磁盘上我的全部可用空间74GB 。在上次运行程序之前,我进行了碎片整理。

我该如何摆脱这个错误?

感谢

编辑: Screen available here

EDIT2:堆栈跟踪

 at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) 
    at System.IO.FileStream.WriteCore(Byte[] buffer, Int32 offset, Int32 count) 
    at System.IO.FileStream.FlushWrite(Boolean calledFromFinalizer) 
    at System.IO.FileStream.Dispose(Boolean disposing) 
    at System.IO.FileStream.Finalize() 

link to another screen

+1

你试图写多少? –

+0

你想写什么位置? –

+0

当错误开始时,它可能大约有10万个产品(40MB)。现在我从零开始,仍然发生.. wtf .. 250产品,我得到错误(大概50kb) – user1085907

回答

1

什么是你的异常堆栈有趣的是,当你调用“错误发生关闭“方法,并在内部调用”刷新“。但是,您已经成功地在代码中的前一行成功调用了“Flush”。所以我期望在明确的“Flush()”调用上抛出存储异常。 这引起了对实际错误原因的怀疑。我想要做的事情: 1.将“一次性”包装在“正在使用”块中 2.不要明确调用“Flush()”,因为在Dispose/Close期间无论如何都会调用该方法。

如果仍然失败,请在写入数据之前尝试记录您尝试写入的驱动器当前的可用空间。以下方法将帮助你:

private static long GetAvailableSpace(string path) 
    { 
     string drive = Path.GetPathRoot(Path.GetFullPath(path)); 
     DriveInfo driveInfo = new DriveInfo(drive); 
     return driveInfo.AvailableFreeSpace; 
    } 

希望这会有所帮助。

+0

好的,谢谢我会试试:) – user1085907