如何将下载的文件保存到指定路径?

时间:2017-03-02 21:39:07

标签: c# .net microsoft-graph

使用files = await graphClient.Me.Drive.Root.ItemWithPath(Path).Children.Request().GetAsync();

下载的文件保存在C:\Users\someone\AppData\Local\Packages\4a9bc9b3-6484-4443-9a65-f36f7519b1d5_9b10f1p8kdmhr\AC\INetCache\3HUY71XE

public static async Task<System.IO.Stream > GetCurrentUserFileAsync(string Path, string FileName)
{
    IDriveItemChildrenCollectionPage files = null;
    try
    {
        var graphClient = AuthenticationHelper.GetAuthenticatedClient();
        files = await graphClient.Me.Drive.Root.ItemWithPath(Path).Children.Request().GetAsync();
        foreach (DriveItem item in files)
        {

            Debug.WriteLine("Got file: " + item.Name);
            if (item.Name == FileName )
            {
                var fileContent = await DownloadFileAsync(item.Id);
                return fileContent ;
            }
        }

        return null;

    }

    catch (ServiceException e)
    {
        Debug.WriteLine("We could not get user files: " + e.Error.Message);
        return null;
    }


}

// Downloads the content of an existing file.
public static async Task<Stream> DownloadFileAsync(string fileId)
    {
        Stream fileContent = null;

        try
        {
            var graphClient = AuthenticationHelper.GetAuthenticatedClient();
            var downloadedFile = await graphClient.Me.Drive.Items[fileId].Content.Request().GetAsync();
            fileContent = downloadedFile;
            Debug.WriteLine("Downloaded file content for file: " + fileId);


        }

        catch (ServiceException e)
        {
            Debug.WriteLine("We could not download the file. The request returned this status code: " + e.Error.Message);
            return null;
        }

        return fileContent;
    }

2 个答案:

答案 0 :(得分:1)

完整的解决方案是使用ApplicationData.Current.LocalFolder.Path来使用此代码,因为我们不允许在其他任何地方写文件,然后写入应用程序的相对路径:

 public static async Task<bool> TryDownloadFileAtPathAsync()
    {
        var createdFileId = await UserSnippets.CreateFileAsync(Guid.NewGuid().ToString(), STORY_DATA_IDENTIFIER);
        var fileContent = await UserSnippets.GetCurrentUserFileAsync("/Documents","Imp.zip") ;
        using (var fileStream = await Task.Run(() => System.IO.File.Create(ApplicationData.Current.LocalFolder.Path + "\\Imp.zip")))
        {
            fileContent.Seek(0, SeekOrigin.Begin);
            fileContent.CopyTo(fileStream);
        }
       return fileContent != null;
    }

有关应用程序相对路径的详细信息,可以查看此页面:ApplicationData Class

谢谢@RasmusW

答案 1 :(得分:0)

如果await DownloadFileAsync(item.Id)在结果流中检索文件,那么由方法GetCurrentUserFileAsync的调用者决定是否在某处写入流内容。

可以使用此代码

完成
var fileContent = await GetCurrentUserFileAsync(onedrivepath, onedrivefilename);
using (var fileStream = File.Create("C:\\localpath\\localfilename"))
{
    fileContent.Seek(0, SeekOrigin.Begin);
    fileContent.CopyTo(fileStream);
}