Convert path to file system path on windows

FreeSlave freeslave93 at gmail.com
Thu Jun 21 20:05:46 UTC 2018


On Thursday, 21 June 2018 at 18:46:05 UTC, Dr.No wrote:
> How can I do that with D?
>
> In C# you can do that:
>
> var filename = @"C:\path\to\my\file.txt";
> var file = new Uri(filename).AbsoluteUri;
> // file is "file:///C:/path/to/my/file.txt"
>
> How can I do that in D?

import std.stdio;
import std.exception;
import core.sys.windows.windows;
import std.windows.syserror;

@safe void henforce(HRESULT hres, lazy string msg = null, string 
file = __FILE__, size_t line = __LINE__)
{
     if (hres != S_OK)
         throw new WindowsException(hres, msg, file, line);
}

@trusted wstring absoluteUri(string path)
{
     import std.path : absolutePath;
     import std.utf : toUTF16z;
     import core.sys.windows.shlwapi;
     import core.sys.windows.wininet;

     auto shlwapi = wenforce(LoadLibraryA("Shlwapi"), "Failed to 
load shlwapi");
     enforce(shlwapi !is null);
     auto urlCreateFromPath = 
cast(typeof(&UrlCreateFromPathW))wenforce(shlwapi.GetProcAddress("UrlCreateFromPathW"), "Failed to find UrlCreateFromPathW");
     scope(exit) FreeLibrary(shlwapi);
     wchar[INTERNET_MAX_URL_LENGTH] buf;
     auto size = cast(DWORD)buf.length;
     henforce(urlCreateFromPath(path.absolutePath.toUTF16z, 
buf.ptr, &size, 0));
     return buf[0..size].idup;
}

int main(string[] args)
{
     foreach(path; args)
     {
         writeln(absoluteUri(path));
     }
	return 0;
}



More information about the Digitalmars-d-learn mailing list