ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

GetUri

Get the uri to an file

Source

public static class StorageFileExtensions
{
    public static Uri GetUri(this IStorageFile file)
    {
        return new Uri(string.Format("ms-appdata:///{0}", FindFilePath(file)));
    }

    private static string FindFilePath(IStorageFile file)
    {
        string pathLocalFolder = ApplicationData.Current.LocalFolder.Path;
        string pathRoamingFolder = ApplicationData.Current.RoamingFolder.Path;

        if (file.Path.StartsWith(pathLocalFolder))
        {
            return GeneratePath("local", file.Path, pathLocalFolder);
        }
        if (file.Path.StartsWith(pathRoamingFolder))
        {
            return GeneratePath("roaming", file.Path, pathLocalFolder);
        }
        throw new ArgumentException("file not compatible");
    }

    private static string GeneratePath(string type, string fullpath, string containerPath)
    {
        var path = fullpath.Substring(containerPath.Length);
        return string.Format("{0}{1}", type, path.Replace('\\', '/'));
    }
}

Example

var newfolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("new folder");
var newfile = await newfolder.CreateFileAsync("testfile");
Uri uri = newfile.GetUri();

Author: Dave Smits

Submitted on: 6 mei 2014

Language: C#

Type: StorageFile

Views: 5146