KeiStory

WPF 디스크 사용량 표시하기

 

디스크의 남은 용량을 나타내는 코드입니다.

 

MainWindow.xaml

<Window x:Class="WPFTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPFTest"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <StackPanel x:Name="stackPanel">
        <Label Content="전체 하드디스크 용량" HorizontalAlignment="Center" VerticalAlignment="Top"/>
        <Button x:Name="calButton" Content="계산하기" Width="200" Margin="0,0,0,20" Click="calButton_Click"/>
    </StackPanel>
</Window>

 

MainWindow.xaml.cs

using System.IO;
using System.Windows;
using System.Windows.Controls;

namespace WPFTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 계산하기 버튼 클릭 이벤트입니다.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void calButton_Click(object sender, RoutedEventArgs e)
        {
            DriveInfo[] driveInfos = DriveInfo.GetDrives();

            foreach (DriveInfo driveInfo in driveInfos)
            {
                if (driveInfo.DriveType == DriveType.Fixed)
                {
                    ProgressBar progressBar = new ProgressBar() { HorizontalAlignment = HorizontalAlignment.Center };

                    // 전체 용량을 계산합니다.
                    progressBar.Maximum = Convert.ToInt32(driveInfo.TotalSize / 1024 / 1024);

                    // 남은 용량을 계산합니다. (MB)
                    progressBar.Value = Convert.ToInt32(driveInfo.TotalSize / 1024 / 1024) - Convert.ToInt32(driveInfo.AvailableFreeSpace / 1024 / 1024);
                    progressBar.Width = 200;
                    progressBar.Height = 20;

                    this.stackPanel.Children.Add(progressBar);

                    Label label = new Label() { HorizontalAlignment = HorizontalAlignment.Center };
                    label.Content = driveInfo.Name + " " + (driveInfo.TotalFreeSpace / 1024 / 1024) + "MB Free";

                    this.stackPanel.Children.Add(label);
                }
            }
        }
    }
}

계산하기 버튼을 클릭하면 디스크 남은 용량이 나열됩니다.

 

 

반응형

공유하기

facebook twitter kakaoTalk kakaostory naver band