将字节数组文件写入OneDrive

时间:2018-09-09 11:12:26

标签: uwp microsoft-graph onedrive

好的,所以我想出了如何从OneDrive for Business中获取文件,并使用以下代码将其写入计算机上的本地目录:

    public static async Task GetFileAsync()
    {
        var (authResult, message) = await Authentication.AquireTokenAsync();
        var httpClient = new HttpClient();
        HttpResponseMessage response;
        var request = new HttpRequestMessage(HttpMethod.Get, MainPage.fileurl);
        request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authResult.AccessToken);
        response = await httpClient.SendAsync(request);
        byte[] fileBytes = await response.Content.ReadAsByteArrayAsync();
        StorageLibrary videoLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Videos);
        string saveFolder = videoLibrary.SaveFolder.Path;
        string genName = App.Generator;
        genName = genName.Replace(" ", "-");
        string saveFileName = App.Date + "-" + App.StartTime + "-" + App.IBX + "-" + genName + ".xlsx";
        saveLocation = saveFolder + "\\" + saveFileName;

        using (MemoryStream stream = new MemoryStream())
        {
            stream.Write(fileBytes, 0, (int)fileBytes.Length);
            using (spreadsheetDoc = SpreadsheetDocument.Open(stream, true))
            {
                await Task.Run(() =>
                {
                    File.WriteAllBytes(saveLocation, stream.ToArray());
                    return TaskStatus.RanToCompletion;
                });
            }
        }
    }

将文件保存到本地计算机后,便能够成功编辑文件并保存编辑。

我弄清楚了如何将其放入字节数组,以及一旦创建数组后如何删除本地文件夹中的已编辑文件。现在,我想将此新编辑的文件(字节数组)写回到OneDrive子文件夹中。

到目前为止,我的代码如下:

    public static async Task PutFileAsync()
    {
        string genName = App.Generator;
        genName = genName.Replace(" ", "-");
        StorageLibrary videoLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Videos);
        string readFolder = videoLibrary.SaveFolder.Path;
        StorageFolder videoFolder = await StorageFolder.GetFolderFromPathAsync(readFolder);
        string readFileName = App.Date + "-" + App.StartTime + "-" + App.IBX + "-" + genName + ".xlsx";
        StorageFile readFile = await videoFolder.GetFileAsync(readFileName);            

进行了一些更改:

        var (authResult, message) = await Authentication.AquireTokenAsync();
        var httpClient = new HttpClient();
        HttpResponseMessage response;
        string posturl = MainPage.spfileurl + readFile.Name + ":/content";
        var content = JsonConvert.SerializeObject(readFile);
        var request = new HttpRequestMessage(HttpMethod.Put, posturl);
        request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authResult.AccessToken);
        request.Content = new StringContent(content, Encoding.UTF8, "application/json");
        response = await httpClient.SendAsync(request);
        var responseString = await response.Content.ReadAsStringAsync();
        await Task.Run(() =>
        {
            File.Delete(readFile.Path);
            return TaskStatus.RanToCompletion;
        });

最后一部分也与another post of mine绑定。

1 个答案:

答案 0 :(得分:2)

您需要将json字符串/纯文本作为请求正文传递,而不是二进制数组(在您的情况下,只需读取本地文件的实际内容,然后将内容传递给json)。

如果您更新文件内容,则可以使用update api

另一种方法:先将delete的旧文件放在云端硬盘中,将upload的最新文件放在最新版本中。

根据您的代码在 MVC 上添加一些有效的代码(关键点 request.Content = new ByteArrayContent ):

 // Initialize the GraphServiceClient.
            GraphServiceClient graphClient = SDKHelper.GetAuthenticatedClient();

            var httpClient = new HttpClient();
            HttpResponseMessage response;
            //string posturl = MainPage.spfileurl + readFile.Name + ":/content";
            string posturl = "https://graph.microsoft.com/v1.0/me/drive/root:/Test.docx:/content";
            //System.IO.FileStream file = System.IO.File.Open(@"D:\TestDocs\Allin.docx", FileMode.Open);             
            //string text= System.IO.File.ReadAllText(@"D:\TestDocs\Allin.docx",Encoding.Unicode);
            //var content = JsonConvert.SerializeObject(file);
            var request1 = new HttpRequestMessage(HttpMethod.Put, posturl);
            string accessToken = await SampleAuthProvider.Instance.GetUserAccessTokenAsync();
            request1.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
            //request1.Content = new StringContent(content, Encoding.UTF8, "application/json");
            request1.Content = new ByteArrayContent(System.IO.File.ReadAllBytes(@"D:\TestDocs\Allin.docx"));//  StringContent(text, Encoding.UTF8); 
            response = await httpClient.SendAsync(request1);
            var responseString = await response.Content.ReadAsStringAsync();
            await Task.Run(() =>
            {
                // System.IO.File.Delete(readFile.Path);
                return TaskStatus.RanToCompletion;
            });