如何获取UWP项目的根文件夹路径



要使用NLog库创建日志文件,我们必须获取特定平台的根文件夹路径。

在iOS中,我们可以通过以下方式获得:

[assembly: Dependency(typeof(GetRootFolder))]
namespace Sample.iOS.DependencyServices
{
public class GetRootFolder : IGetRootFolder
{
string IGetRootFolder.GetRootFolder()
{
string folder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
return folder;
}
}
}

对于Android,我们有这样的方式:

[assembly: Dependency(typeof(GetRootFolder))]
namespace Sample.Droid.DependencyServices
{
public class GetRootFolder : IGetRootFolder
{
string IGetRootFolder.GetRootFolder()
{
var folder = $"{Android.OS.Environment.GetExternalStoragePublicDirectory("Log").CanonicalPath}";
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
return folder;
}
}
}

如何在Xamarin.Forms中获取UWP项目的文件夹路径

在UWP中,您可以使用下面的代码来获取应用程序的安装文件夹。

[assembly: Dependency(typeof(GetPath))]
namespace App1.UWP
{
class GetPath : IGetPath
{
public void Getpath()
{
// Get the app's installation folder.
StorageFolder appFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
// Print the folder's path to the Visual Studio Output window.
Debug.WriteLine(appFolder.Name + " folder path: " + appFolder.Path);
}
}
}