tags:

views:

1008

answers:

3

In Delphi there is a function ExpandUNCFileName that takes in a filename and converts it into the UNC equivalent. It expands mapped drives and skips local and already expanded locations.

Samples

C:\Folder\Text.txt -> C:\Folder\Text.txt
L:\Folder\Sample.txt -> \\server\Folder1\Folder\Sample.txt Where L: is mapped to \\server\Folder1\
\\server\Folder\Sample.odf -> \server\Folder\Sample.odf

Is there a simple way to do this in C# or will I have to use windows api call WNetGetConnection and then manually check the ones that wouldn't get mapped?

A: 

There is no built-in function in the BCL which will do the equivalent. I think the best option you have is pInvoking into WNetGetConnection as you suggested.

JaredPar
+1  A: 

P/Invoke WNetGetUniversalName().

I've done it modifying this code from www.pinvoke.net.

Jay Riggs
A: 

Try this code, is written in Delphi .Net

you must translate it to c #

function WNetGetUniversalName; external;
[SuppressUnmanagedCodeSecurity, DllImport(mpr, CharSet = CharSet.Ansi, SetLastError = True, EntryPoint = 'WNetGetUniversalNameA')]


function ExpandUNCFileName(const FileName: string): string;

function GetUniversalName(const FileName: string): string;
const
UNIVERSAL_NAME_INFO_LEVEL = 1;    
var
  Buffer: IntPtr;
  BufSize: DWORD;
begin
  Result := FileName;
  BufSize := 1024;
  Buffer := Marshal.AllocHGlobal(BufSize);
  try
    if WNetGetUniversalName(FileName, UNIVERSAL_NAME_INFO_LEVEL,
      Buffer, BufSize) <> NO_ERROR then Exit;
    Result := TUniversalNameInfo(Marshal.PtrToStructure(Buffer,
      TypeOf(TUniversalNameInfo))).lpUniversalName;
  finally
    Marshal.FreeHGlobal(Buffer);
  end;
end;

begin
  Result :=System.IO.Path.GetFullPath(FileName);
  if (Length(Result) >= 3) and (Result[2] = ':') and (Upcase(Result[1]) >= 'A')
    and (Upcase(Result[1]) <= 'Z') then
    Result := GetUniversalName(Result);
end;

Bye.

RRUZ
very nice thanks so much
Anonymous Type