SaveFileDialog在关闭窗口之前检查可用空间

时间:2019-04-08 06:26:46

标签: c# wpf winforms

我试图弄清楚如果没有足够的空间要保存时如何有效地防止保存数据。

是否可以不关闭SaveFileDialog窗口并向用户显示消息?

1 个答案:

答案 0 :(得分:0)

这将完成您要达到的目标。与您的请求的唯一区别是,在打开对话框时,而不是在实际选择文件之后,您将不进行检查。随时根据您的需要修改此代码

    //Call this function instead of SaveFileDialog.Show()
    void showSaveDialog()
    {
        //Open dialog
        SaveFileDialog sfd = new SaveFileDialog();
        sfd.ShowDialog();
        //check if file exists
        if (!File.Exists(sfd.FileName))
        {
            return;
        }
        // get the harddrive the user is saving on and get the free space
        string drive = System.IO.Path.GetPathRoot(sfd.FileName);
        double freeSpace = getFreeSpace(drive);
        double filesize = new System.IO.FileInfo(sfd.FileName).Length;

        //Messagebox if the is not enought space and restart
        if (  filesize > freeSpace)
        {
            MessageBox.Show($"Not enough free space on harddrive {drive}...\nFree space was {freeSpace} and file was {filesize}","Storage Error");
            showSaveDialog();
        }
        else
        {
            //save your file here
        }

    }

    double getFreeSpace(string drive)
    {
        DriveInfo[] allDrives = DriveInfo.GetDrives();

        foreach (DriveInfo d in allDrives)
        {
            if (d.Name==drive)
            {
                return d.AvailableFreeSpace;
            }
        }
        return 0;
    }