Microsoft Graph SDK C#: использование FileSavePicker с Onedrive
Можно ли использовать объект FileSavePicker для сохранения файла в Onedrive с помощью Microsoft Graph SDK для C#.
Причина в том, что мне нужно, чтобы пользователь выбрал, где будет храниться файл резервной копии данных.
Используя следующий исходный код, я могу загрузить или загрузить файл, но не предлагая пользователю выбрать нужный путь.
Authentication.cs
internal class Authentication
{
internal static GraphServiceClient GetAuthenticatedClient()
{
if (Settings.graphClient == null)
{
try
{
Settings.graphClient = new GraphServiceClient("https://graph.microsoft.com/v1.0", new DelegateAuthenticationProvider(
async (requestMessage) =>
{
var token = await GetTokenForUserAsync();
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
})
);
return Settings.graphClient;
}
catch (Exception)
{ }
}
return Settings.graphClient;
}
internal static async Task<string> GetTokenForUserAsync()
{
AuthenticationResult authResult;
try
{
authResult = await Settings.IdentityClientApp.AcquireTokenSilentAsync(Settings.Scopes);
Settings.TokenForUser = authResult.Token;
}
catch (Exception)
{
if (Settings.TokenForUser == null || Settings.Expiration <= DateTimeOffset.UtcNow.AddMinutes(5))
{
authResult = await Settings.IdentityClientApp.AcquireTokenAsync(Settings.Scopes);
Settings.TokenForUser = authResult.Token;
Settings.Expiration = authResult.ExpiresOn;
}
}
return Settings.TokenForUser;
}
internal static void SignOut()
{
foreach (var user in Settings.IdentityClientApp.Users)
user.SignOut();
Settings.graphClient = null;
Settings.TokenForUser = null;
}
}
Settings.cs
internal class Settings
{
public static string clientId = "xxxxxx-xxxx-xxx-xxx-xxxxxxxxx";
public static string[] Scopes = {
"https://graph.microsoft.com/User.Read",
"https://graph.microsoft.com/Mail.Send",
"https://graph.microsoft.com/Files.ReadWrite.All",
"https://graph.microsoft.com/Files.ReadWrite" };
public static PublicClientApplication IdentityClientApp = new PublicClientApplication(clientId);
public static string TokenForUser = null;
public static DateTimeOffset Expiration;
public static GraphServiceClient graphClient = null;
}
Скачать файл
public static async Task<bool> Download(string file, string to)
{
try
{
var download = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(file), Uri.EscapeUriString(System.IO.Path.GetFileName(file)));
using (Stream stream = await Authentication.GetAuthenticatedClient().Me.Drive.Root.ItemWithPath(download).Content.Request().GetAsync())
{
try
{
using (FileStream writer = new FileStream(to, FileMode.Create))
{
}
using (StreamReader reader = new StreamReader(stream))
{
await PathIO.WriteTextAsync(to, reader.ReadToEnd());
}
return true;
}
catch (Exception)
{
return false;
}
}
}
catch (Exception)
{
return false;
}
}
1 ответ
Решение
Ваш вопрос мне не совсем понятен; Я понимаю, что вы хотите использовать FilePicker с приложением OneDrive, а затем заставить пользователя выбрать цель в OneDrive?
Это невозможно. Я думаю, что лучшим подходом было бы создать собственный пользовательский интерфейс, чтобы позволить пользователю выбрать папку и использовать код, указанный выше, для сохранения файла резервной копии в onedrive.