c#“磁盘上没有足够的空间”实际上有

时间:2017-03-16 08:57:43

标签: c# filestream diskspace

我有每分钟写入文件的应用程序。有时(每10分钟+ - )我收到错误

  

磁盘空间不足

我的应用是Windows窗体应用。我在谷歌上阅读了很多文章,但它没有给我任何结果如何解决它。

例外:

  

抛出异常:mscorlib.dll中的“System.IO.IOException”

我的代码:

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:Stacktrace

     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 :(得分:1)

异常堆栈的有趣之处在于,当您调用"关闭"方法,并调用" Flush"内部。但是,您已经成功调用了" 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;
    }

希望这有帮助。