How to check for available space using MTP (Media Transfer Protocol) with Delphi?

How to check for available space?
For example, unable to copy file to Mobile Device. There is an Mobile Device Copy Error. It is necessary to find out the reason, whether it happened because of a lack of available space.
Michael VlasenkoAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Sinisa VukSoftware architectCommented:
With help of using PortableDeviceApi tlb (MS) unit ... you can get storage size and free space too.
I examine MS blog example...

uses ... PortableDeviceApiLib_TLB;
....

const
  //storage
  WPD_STORAGE_ACCESS_CAPABILITY_FMTID : TGuid = '{01a3057a-74d6-4e80-bea7-dc4c212ce50a}';
  WPD_STORAGE_ACCESS_CAPABILITY_PID = 11;

  WPD_STORAGE_CAPACITY_FMTID : TGuid = '{01a3057a-74d6-4e80-bea7-dc4c212ce50a}';
  WPD_STORAGE_CAPACITY_PID = 4;         

  WPD_STORAGE_CAPACITY_IN_OBJECTS_FMTID : TGuid = '{01a3057a-74d6-4e80-bea7-dc4c212ce50a}';
  WPD_STORAGE_CAPACITY_IN_OBJECTS_PID = 10;

  WPD_STORAGE_DESCRIPTION_FMTID : TGuid = '{01a3057a-74d6-4e80-bea7-dc4c212ce50a}';
  WPD_STORAGE_DESCRIPTION_PID = 7;

  WPD_STORAGE_FILE_SYSTEM_TYPE_FMTID : TGuid = '{01a3057a-74d6-4e80-bea7-dc4c212ce50a}';
  WPD_STORAGE_FILE_SYSTEM_TYPE_PID = 3;

  WPD_STORAGE_FREE_SPACE_IN_BYTES_FMTID : TGuid = '{01a3057a-74d6-4e80-bea7-dc4c212ce50a}';
  WPD_STORAGE_FREE_SPACE_IN_BYTES_PID = 5;

  WWPD_STORAGE_FREE_SPACE_IN_OBJECTS_FMTID : TGuid = '{01a3057a-74d6-4e80-bea7-dc4c212ce50a}';
  WPD_STORAGE_FREE_SPACE_IN_OBJECTS_PID = 6;

  WPD_STORAGE_MAX_OBJECT_SIZE_FMTID : TGuid = '{01a3057a-74d6-4e80-bea7-dc4c212ce50a}';
  WPD_STORAGE_MAX_OBJECT_SIZE_PID = 9;

  WPD_STORAGE_SERIAL_NUMBER_FMTID : TGuid = '{01a3057a-74d6-4e80-bea7-dc4c212ce50a}';
  WPD_STORAGE_SERIAL_NUMBER_PID = 8;

  WPD_STORAGE_TYPE_FMTID : TGuid = '{01a3057a-74d6-4e80-bea7-dc4c212ce50a}';
  WPD_STORAGE_TYPE_PID = 2;

  //*****
  WPD_DEVICE_OBJECT_ID = 'DEVICE';
....

type
  PStorageInfo = ^TStorageInfo;
  TStorageInfo = record
    StorageId: String[255];
    lStorageFreeSpace: Int64;
    lStorageTotalSpace: Int64;
  end;

  TStorageInfoArray = array of TStorageInfo;

...

function ConnectToDevice(sDev: WideString; var PortableDev: IPortableDevice; DbgLst: TStringList): Boolean;
var
  PortableDeviceValues: IPortableDeviceValues;
  hr: HResult;
  dev_val: PortableDeviceApiLib_TLB._tagpropertykey;
  //bReadonly: Boolean;
begin
  Result := False;

  if Assigned(DbgLst) then
    DbgLst.Add('Start Connecting: '+sDev);

  PortableDev := CoPortableDevice.Create;
  try
    //create device values:
    PortableDeviceValues := CreateComObject(CLASS_PortableDeviceValues) as IPortableDeviceValues;
    if VarIsClear(PortableDeviceValues) then Exit;

    if Assigned(DbgLst) then
      DbgLst.Add('Dev. val. ok! ');

    //bReadonly := False;
    //set some info
    dev_val.fmtid := WPD_CLIENT_NAME_FMTID;
    dev_val.pid := WPD_CLIENT_NAME_PID;
    PortableDeviceValues.SetStringValue(dev_val, PWideChar(CLIENT_NAME));

    dev_val.fmtid := WPD_CLIENT_MAJOR_VERSION_FMTID;
    dev_val.pid := WPD_CLIENT_MAJOR_VERSION_PID;
    PortableDeviceValues.SetUnsignedIntegerValue(dev_val, CLIENT_MAJOR_VER);

    dev_val.fmtid := WPD_CLIENT_MINOR_VERSION_FMTID;
    dev_val.pid := WPD_CLIENT_MINOR_VERSION_PID;
    PortableDeviceValues.SetUnsignedIntegerValue(dev_val, CLIENT_MINOR_VER);

    dev_val.fmtid := WPD_CLIENT_REVISION_FMTID;
    dev_val.pid := WPD_CLIENT_REVISION_PID;
    PortableDeviceValues.SetUnsignedIntegerValue(dev_val, CLIENT_REVISION);

    //open device
    hr := PortableDev.Open(PWideChar(sDev), PortableDeviceValues);
    if hr = E_ACCESSDENIED then
    begin
      // Attempt to open for read-only access
      dev_val.fmtid := WPD_CLIENT_DESIRED_ACCESS_FMTID;
      dev_val.pid := WPD_CLIENT_DESIRED_ACCESS_PID;
      PortableDeviceValues.SetUnsignedIntegerValue(dev_val, GENERIC_READ);
      hr := PortableDev.Open(PWideChar(sDev), PortableDeviceValues);
      //bReadonly := (hr = S_OK);
    end;

    //opened ok
    if hr = S_OK then
    begin
      if Assigned(DbgLst) then
        DbgLst.Add('Connected: '+sDev);
      Result := True;
    end
    else
    begin
      if Assigned(DbgLst) then
        DbgLst.Add('Not connected: '+IntToStr(hr));
    end;
  finally
    PortableDeviceValues := nil;
  end;
end;

function GetFirstStorageID(PortableDev: IPortableDevice; DbgLst: TStringList): WideString;
var
  content: IPortableDeviceContent;
  objectIds: IEnumPortableDeviceObjectIDs;
  objectId: PWideChar;
  fetched: Cardinal;
begin
  Result := WPD_DEVICE_OBJECT_ID;
  if PortableDev.Content(content) = S_OK then
  begin
    if content.EnumObjects(0, '', nil, objectIds) = S_OK then
    begin
      objectIds.Reset;
      objectIds.Next(1, objectId, fetched);
      if (fetched > 0) then
        Result := objectId;
    end;
  end;
  
  if Assigned(DbgLst) then
    DbgLst.Add('Device root: '+ Result);
end;

function GetDevDescription(PMan: TPortableDeviceManager; sDeviceId: WideString; DbgLst: TStringList): WideString;
var
  iDevNameLen: LongWord;
  iRes: Integer;
begin
  //get length of friendly name:
  iDevNameLen := 0;
  Result := '';

  iRes := PMan.GetDeviceDescription(PWideChar(sDeviceId), Word(nil^), iDevNameLen);
  if iRes = S_OK then
  begin
    if Assigned(DbgLst) then
      DbgLst.Add('DeviceDescription len='+IntToStr(iDevNameLen));

    //Get Description
    if iDevNameLen>0 then
    begin
      SetLength(Result, iDevNameLen);
      ZeroMemory(PWideChar(Result), iDevNameLen);
      PMan.GetDeviceDescription(PWideChar(sDeviceId), PWord(PWideChar(Result))^, iDevNameLen);
      Result := Trim(Result);
      if Assigned(DbgLst) then
        DbgLst.Add('DeviceDescription='+Result);
    end;
  end
  else
  begin
    if Assigned(DbgLst) then
      DbgLst.Add('Cannot GetDeviceDescription! ('+IntToStr(iRes)+')');
  end;
end;

function GetDeviceFriendlyName(PMan: TPortableDeviceManager; sDeviceId: WideString; DbgLst: TStringList): WideString;
var
  iDevNameLen{, iType}: LongWord;
  iRes: Integer;
begin
  //get length of friendly name:
  iDevNameLen := 0;
  Result := '';

  iRes := PMan.GetDeviceFriendlyName(PWideChar(sDeviceId), Word(nil^), iDevNameLen);
  if iRes = S_OK then
  begin
    if Assigned(DbgLst) then
      DbgLst.Add('FriendlyName len='+IntToStr(iDevNameLen));

    //Get Friendly Name
    if iDevNameLen>0 then
    begin
      SetLength(Result, iDevNameLen);
      ZeroMemory(PWideChar(Result), iDevNameLen);
      PMan.GetDeviceFriendlyName(PWideChar(sDeviceId), PWord(PWideChar(Result))^, iDevNameLen);
      Result := Trim(Result);
      if Assigned(DbgLst) then
        DbgLst.Add('FriendlyName='+Result);
    end;
  end
  else
  begin
    if Assigned(DbgLst) then
      DbgLst.Add('Cannot GetDeviceFriendlyName! ('+IntToStr(iRes)+')');

    Result := GetDevDescription(PMan, sDeviceId, DbgLst);
  end;
end;

procedure GetDeviceStorageInfo(sDeviceId, parentID: WideString; var StorageInfo: TStorageInfoArray;
  DbgLst: TStringList);
var
  PortableDev: IPortableDevice;
  content: IPortableDeviceContent;
  prop: IPortableDeviceProperties;
  prop_val: IPortableDeviceValues;
  propKeys_val: PortableDeviceApiLib_TLB._tagpropertykey;
  objectIds: IEnumPortableDeviceObjectIDs;
  objectId: PWideChar;
  fetched: Cardinal;
  propKeys: IPortableDeviceKeyCollection;
  info: TStorageInfo;
begin
  //clear...
  SetLength(StorageInfo, 0);
  try
    if ConnectToDevice(sDeviceId, PortableDev, DbgLst) then
    begin
      //read content of device
      try
        if PortableDev.Content(content) = S_OK then
        begin
          if parentID='' then
            parentID := GetFirstStorageID(PortableDev, DbgLst);

          //get content properties
          content.Properties(prop);
                                        //DEVICE
          if content.EnumObjects(0, PWideChar(parentID), nil, objectIds) = S_OK then
          begin
            objectIds.Reset;
            while objectIds.Next(1, objectId, fetched) = S_OK do    //list all storages under DEVICE
            begin
              if (fetched > 0) then
              begin
                propKeys := CreateComObject(CLSID_PortableDeviceKeyCollection) as IPortableDeviceKeyCollection;
                if VarIsClear(propKeys) then Exit;

                try
                  //add props we want to get
                  propKeys_val.fmtid := WPD_STORAGE_CAPACITY_FMTID; //CAPACITY
                  propKeys_val.pid := WPD_STORAGE_CAPACITY_PID;
                  propKeys.Add(propKeys_val);

                  propKeys_val.fmtid := WPD_STORAGE_FREE_SPACE_IN_BYTES_FMTID; //FREE
                  propKeys_val.pid := WPD_STORAGE_FREE_SPACE_IN_BYTES_PID;
                  propKeys.Add(propKeys_val);

                  //get values
                  prop.GetValues(PWideChar(objectId), propKeys, prop_val);
                  //check....
                  if not VarIsClear(prop_val) then
                  begin
                    //init info record
                    ZeroMemory(@info, SizeOf(TStorageInfo));
                    info.StorageId := String(objectId);  //keep storage id

                    propKeys_val.fmtid := WPD_STORAGE_CAPACITY_FMTID; //CAPACITY
                    propKeys_val.pid := WPD_STORAGE_CAPACITY_PID;

                    //prop_val.GetStringValue(propKeys_val, ObjVal);
                    prop_val.GetUnsignedLargeIntegerValue(propKeys_val, info.lStorageTotalSpace);
                    if Assigned(DbgLst) then
                      DbgLst.Add('WPD_STORAGE_CAPACITY ('+objectId+'): '+ IntToStr(info.lStorageTotalSpace));

                    propKeys_val.fmtid := WPD_STORAGE_FREE_SPACE_IN_BYTES_FMTID;
                    propKeys_val.pid := WPD_STORAGE_FREE_SPACE_IN_BYTES_PID;

                    prop_val.GetUnsignedLargeIntegerValue(propKeys_val, info.lStorageFreeSpace);
                    if Assigned(DbgLst) then
                      DbgLst.Add('WPD_STORAGE_FREE_SPACE_IN_BYTES ('+objectId+'): '+ IntToStr(info.lStorageFreeSpace));
                      
                    //keep 4 later
                    SetLength(StorageInfo, Length(StorageInfo)+1);
                    StorageInfo[High(StorageInfo)] := info;
                  end;
                finally

                end;
              end
              else
                Break;
            end; //while
          end;
        end;
      finally
        PortableDev.Close;
      end;
    end;
  finally
    PortableDev := nil;
  end;
end;

Open in new window


usage:
sDevId := GetDeviceId;
  if Length(sDevId) > 0 then
  begin
    GetDeviceStorageInfo(sDevId, '', StorageInfo, TStringList(Memo1.Lines));
  end;

Open in new window


Main part of code relies on older code made as result of this question...

As I test with my phone - which have two partition (internal, external) - made example which support this - so get free space for both.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Michael VlasenkoAuthor Commented:
Thank you for leaving line 272. Thanks, that you did not delete it, but just commented out. I did not succeed with the GetUnsignedLargeIntegerValue, but it turned out using the GetStringValue method.
0
Sinisa VukSoftware architectCommented:
Do you get any error with GetUnsignedLargeIntegerValue? or just return 0?
0
OWASP: Threats Fundamentals

Learn the top ten threats that are present in modern web-application development and how to protect your business from them.

Michael VlasenkoAuthor Commented:
I'm can not running compilation and the error message pops up:
Types of actual and formal var parameters must be identical.
0
Sinisa VukSoftware architectCommented:
Maybe wrong PortableDeviceApi lib. Can you drop your PortableDeviceApiLib_TLB.pas here?
0
Michael VlasenkoAuthor Commented:
You're right. The reason is this. I looked in PortableDeviceApiLib_TLB.pas and saw:
    function GetUnsignedLargeIntegerValue(var key: _tagpropertykey; out pValue: Largeuint): HResult; stdcall;

Open in new window

I made changes to the lines 44, 45:
      lStorageFreeSpace: Largeuint;
      lStorageTotalSpace: Largeuint;

Open in new window

After that, the compilation was successful...
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Delphi

From novice to tech pro — start learning today.