2009-05-13 9 views
8

Sto costruendo una piccola app che mi dà lo spazio libero disponibile sui miei dischi.Per codice, come posso verificare se un disco rigido sta dormendo senza svegliarlo

Vorrei aggiungere una funzione che mostra lo stato del disco, se è dormiente o meno, ad esempio. Il sistema operativo è Windows.

Come si può fare? Il codice non dovrebbe avere svegliare il disco per scoprire, ovviamente;)

Una soluzione in C# sarebbe bello ma credo che qualsiasi soluzione farà ...

Grazie per voi aiuto.

risposta

6

soluzione C++ (chiamata GetDiskPowerState e sarà un'iterazione su unità fisiche fino a quando non ci sono più):

class AutoHandle 
{ 
    HANDLE mHandle; 
public: 
    AutoHandle() : mHandle(NULL) { } 
    AutoHandle(HANDLE h) : mHandle(h) { } 

    HANDLE * operator &() 
    { 
     return &mHandle; 
    } 

    operator HANDLE() const 
    { 
     return mHandle; 
    } 

    ~AutoHandle() 
    { 
     if (mHandle && mHandle != INVALID_HANDLE_VALUE) 
      ::CloseHandle(mHandle); 
    } 
}; 


bool 
GetDiskPowerState(LPCTSTR disk, string & txt) 
{ 
    AutoHandle hFile = CreateFile(disk, 0, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); 
    if (hFile && hFile != INVALID_HANDLE_VALUE) 
    { 
     BOOL powerState = FALSE; 
     const BOOL result = GetDevicePowerState(hFile, &powerState); 
     const DWORD err = GetLastError(); 

     if (result) 
     { 
      if (powerState) 
      { 
       txt += disk; 
       txt += " : powered up\r\n"; 
      } 
      else 
      { 
       txt += disk; 
       txt += " : sleeping\r\n"; 
      } 
      return true; 
     } 
     else 
     { 
      txt += "Cannot get drive "; 
      txt += disk; 
      txt += "status\r\n"; 
      return false; 
     } 
    } 

    return false; 
} 

string 
GetDiskPowerState() 
{ 
    string text; 
    CString driveName; 
    bool result = true; 
    for (int idx= 0; result; idx++) 
    { 
     driveName.Format("\\\\.\\PhysicalDrive%d", idx); 
     result = GetDiskPowerState(driveName, text); 
    } 
    return text; 
} 
+0

Grazie, funziona come un fascino. – Jonx

3

E in C# (Da http://msdn.microsoft.com/en-us/library/ms704147.aspx)

// Get the power state of a harddisk 
string ReportDiskStatus() 
{ 
    string status = string.Empty; 
    bool fOn = false; 

    Assembly assembly = Assembly.GetExecutingAssembly(); 
    FileStream[] files = assembly.GetFiles(); 
    if (files.Length > 0) 
    { 
     IntPtr hFile = files[0].Handle; 
     bool result = GetDevicePowerState(hFile, out fOn); 
     if (result) 
     { 
      if (fOn) 
      { 
       status = "Disk is powered up and spinning"; 
      } 
      else 
      { 
       status = "Disk is sleeping"; 
      } 
     } 
     else 
     { 
      status = "Cannot get Disk Status"; 
     } 
     Console.WriteLine(status); 
    } 
    return status; 
} 
+0

Sì, bello ... Manca l'importazione ma il link offre tutto. Grazie. – Jonx

Problemi correlati