Question : Faster network check

Do you have a code faster than that?
Please submit
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}


function checksharedpermission(sharedpath:string; Out netstat:ShortString):boolean;
var
MS:TMemoryStream;
st:char;
netpermis:boolean;
begin
      MS := TMemoryStream.Create;
      st:='x';
      ms.Write(st,1);
      MS.Seek(0,soFromBeginning);
      try
      netpermis:=true;
      ms.SaveToFile(sharedpath + '\x');
      except
       on E : Exception do
       begin
       if pos('denied',e.Message)>0 then netstat:='denied';
       if pos('not found',e.Message)>0 then netstat:='not found';
       netpermis:=false;
       end;
      end;
      ms.Free;
      if netpermis=true then
      deletefile(sharedpath + '\x');
      result := netpermis;
end;


procedure TForm1.Button1Click(Sender: TObject);
var netstat:ShortString;
begin
      if checksharedpermission('\\iserver\gfiles',netstat)=true then
      begin
      showmessage('Shared Folder/Drive is Found and Writable');
      end
      else
      begin
      showmessage('Shared Folder/Drive is '+ netstat);
      end;
end;

end.

Answer : Faster network check

Faster than throwing execeptions. Tested little over 3 seconds with the original, about 1100ms with the code below.

Regards,
Russell

function CheckSharedPermission(SharedPath: String; out NetStat: String): Boolean;
var  hTest:         THandle;
     dwError:       DWORD;
begin

  // Set default result
  result:=False;

  // Clear netstat
  SetLength(NetStat, 0);

  // Create self-deleting test file
  hTest:=CreateFile(PChar(Format('%s\_x%d.tmp', [SharedPath, GetTickCount])), GENERIC_READ or GENERIC_WRITE, 0, nil, CREATE_ALWAYS, FILE_FLAG_DELETE_ON_CLOSE, 0);

  // Check handle
  if (hTest = INVALID_HANDLE_VALUE) then
  begin
     // Get last error
     dwError:=GetLastError;
     // Check result code
     case dwError of
        // File or path not found
        ERROR_FILE_NOT_FOUND,
        ERROR_PATH_NOT_FOUND    :  NetStat:='not found';
        // Permissions error
        ERROR_ACCESS_DENIED     :  NetStat:='denied';
     else
        // Get system error message
        NetStat:=SysErrorMessage(dwError);
     end;
  end
  else
  begin
     // Close the file
     CloseHandle(hTest);
     // Success
     result:=True;
  end;

end;
Random Solutions  
 
programming4us programming4us