How can I convert a UNC Windows file path to a File URI without using any 3rd party tools or by hand?

In a blog post from Microsoft they illustrate how a URI can be written to specify local system file paths.

When sharing the path to network share files some chat programs will open these files in a browser.

So I hand code the changes needed to turn the windows path to a file URI

UNC Windows path: \\sharepoint.business.com\DavWWWRoot\rs\project 1\document.txt

becomes

URI: file://sharepoint.business.com/DavWWWRoot/rs/project%201/document.txt

I am tired of hand coding every time and was wondering if there was a way of quickly converting to a File URI.

I don't have admin permissions on my machine so I can't install software.


Solution 1:

PowerShell is an excellent way to automate tedious recurring tasks like the above!

Using PowerShell

Converting the above UNC path into a file URI is extremely simple using PowerShell (all versions), and requires only the format and replace operators, for example:

$Path = "\\sharepoint.business.com\DavWWWRoot\rs\project 1\document.txt"

# replace back slash characters with a forward slash, url-encode spaces,
# and then prepend "file:" to the resulting string

# note: the "\\" in the first use of the replace operator is an escaped
# (single) back slash, and resembles the leading "\\" in the UNC path
# by coincidence only

"file:{0}" -f ($Path -replace "\\", "/" -replace " ", "%20")

Which yields the following:

file://sharepoint.business.com/DavWWWRoot/rs/project%201/document.txt

As a Reusable Function

Finally, recurring tasks like the above should be made into PowerShell functions whenever possible. This saves time in the future, and ensures each task is always executed in exactly the same way.

The following function is an equivalent of the above:

function ConvertTo-FileUri {
    param (
        [Parameter(Mandatory)]
        [string]
        $Path
    )

    $SanitizedPath = $Path -replace "\\", "/" -replace " ", "%20"
    "file:{0}" -f $SanitizedPath
}

Once the function has been defined (and loaded into the current PowerShell session), simply call the function by name and provide the UNC path to convert as a parameter, for example:

ConvertTo-FileUri -Path "\\sharepoint.business.com\DavWWWRoot\rs\project 1\document.txt"

Solution 2:

The simplest approach is to use the .Net URI class from your PowerShell code:

[System.Uri]'\sharepoint.business.com\DavWWWRoot\rs\project 1\document.txt' will give you a URI, and then the "AbsoluteURI" property will give you that as a string. So:

([System.Uri]'\\sharepoint.business.com\DavWWWRoot\rs\project 1\document.txt').AbsoluteUri

will give you what you want.