Windows Mobile获取存储卡容量及使用情况

 

在做Windows Mobile开发的时候,为了节省空间,很多文件要放到存储卡上,因而对存储卡空间及容量的管理就极为重要。我们可以通过封装GetDiskFreeSpaceEx API来完成该功能,具体C#代码如下。

public static DiskFreeSpace GetDiskFreeSpace(string directoryName)
        {
            DiskFreeSpace result = new DiskFreeSpace();

            if (!GetDiskFreeSpaceEx(directoryName, ref result.FreeBytesAvailable, ref result.TotalBytes, ref result.TotalFreeBytes))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error(), "Error retrieving free disk space");
            }
            return result;
        }

        public struct DiskFreeSpace
        {
            public long FreeBytesAvailable;

            public long TotalBytes;

            public long TotalFreeBytes;
        }

        [DllImport("coredll")]
        private static extern bool GetDiskFreeSpaceEx(string directoryName,
            ref long freeBytesAvailable,
            ref long totalBytes,
            ref long totalFreeBytes);

下面代码用来测试,本人在Windows Mobile5.0 及Windows Mobile6.0的Pocket PC上测试通过。

private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                DiskFreeSpace dis = GetDiskFreeSpace("Storage Card");
                MessageBox.Show("总空间:"+dis.TotalBytes.ToString()+"/r/n剩余空间:"+dis.TotalFreeBytes.ToString()+"/r/n");
            }
            catch (Exception ep)
            {
                MessageBox.Show(ep.Message);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }

原文地址:https://www.cnblogs.com/xyzlmn/p/3168457.html