2014-12-19 53 views
6

我想從C#直接創建一個doc,docx,pptx或excel文件到我的Onedrive帳戶。 我試過這個,但它不適合我。任何人都知道我做錯了什麼?由於從C#編程創建文件到Onedrive?

public async Task<ActionResult> CreateWordFile() 
{ 
    LiveLoginResult loginStatus = await authClient.InitializeWebSessionAsync(HttpContext); 
    if (loginStatus.Status == LiveConnectSessionStatus.Connected) 
    { 
     var fileData = new Dictionary<string, object>(); 
     fileData.Add("name", "Document.docx"); 
     fileData.Add("Content-Type", "multipart/form-data; boundary=A300x"); 
     fileData.Add("type", "file"); 

     LiveOperationResult getResult = await connectedClient.PostAsync("me/skydrive/files", fileData); 
    } 

    return View(); 
} 

編輯: ,我得到的錯誤是這一個:

「頭‘的Content-Type’缺少必要的參數:‘邊界’ 說明:發生未處理的異常在執行當前Web請求期間請檢查堆棧跟蹤以獲取有關該錯誤的更多信息以及源代碼的位置 異常詳細信息:Microsoft.Live.LiveConnectException:頭文件'Content-Type'缺少所需的參數:'邊界'。「

+5

錯誤消息,什麼不工作? – 2014-12-19 11:02:12

+0

確保您已更新爲使用Live SDK 5.6二進制文件。 – sagar43 2014-12-19 11:13:49

+0

我在帖子中輸入了我得到的錯誤信息,並且已經有5.6更新(這不是因爲Live SDK的版本) – CalinCosmin 2014-12-19 11:21:39

回答

1

最後我從c#創建一個docx文件。我把解決方案放在這裏(方法中的代碼不是重構的,因此可以用嚴格的方法分割)。

public async Task<ActionResult> CreateWordFile() 
{ 
    LiveLoginResult loginStatus = await authClient.InitializeWebSessionAsync(HttpContext); 
    if (loginStatus.Status == LiveConnectSessionStatus.Connected) 
    { 
     connectedClient = new LiveConnectClient(this.authClient.Session); 
     string url = "https://apis.live.net/v5.0/me/skydrive/files?access_token=" + this.authClient.Session.AccessToken; 

     MemoryStream streamDoc = new MemoryStream(); 
     DocX doc = DocX.Create(streamDoc); 

     string headlineText = "Constitution of the United States"; 
     string paraOne = "" 
      + "We the People of the United States, in Order to form a more perfect Union, " 
      + "establish Justice, insure domestic Tranquility, provide for the common defence, " 
      + "promote the general Welfare, and secure the Blessings of Liberty to ourselves " 
      + "and our Posterity, do ordain and establish this Constitution for the United " 
      + "States of America."; 

     // A formatting object for our headline: 
     var headLineFormat = new Formatting(); 
     headLineFormat.FontFamily = new System.Drawing.FontFamily("Arial Black"); 
     headLineFormat.Size = 18D; 
     headLineFormat.Position = 12; 

     // A formatting object for our normal paragraph text: 
     var paraFormat = new Formatting(); 
     paraFormat.FontFamily = new System.Drawing.FontFamily("Calibri"); 
     paraFormat.Size = 10D; 

     doc.InsertParagraph(headlineText, false, headLineFormat); 
     doc.InsertParagraph(paraOne, false, paraFormat); 

     doc.Save(); 

     var docFile = File(streamDoc, "application/octet-stream", "FileName.docx"); 
     MemoryStream streamFile = new MemoryStream(); 
     docFile.FileStream.Position = 0; 
     docFile.FileStream.CopyTo(streamFile); 

     var bites = streamFile.ToArray(); 
     Stream stream2 = new MemoryStream(bites); 

     try 
     { 
      LiveOperationResult getResult = await connectedClient.UploadAsync("me/skydrive", docFile.FileDownloadName, stream2, OverwriteOption.Overwrite); 
     } 
     catch(WebException ex) 
     { 

     } 
    } 

    return View("~/Views/Auth/EditFile.cshtml"); 
} 
+0

我如何獲得Microsoft.Live dll? – 2017-02-16 12:05:25

+0

通過nuget包管理器控制檯。檢查那裏,你會發現OneDrive SDK – CalinCosmin 2017-06-12 12:35:45

+0

我在Fab工作。 btw thnx重播:) – 2017-06-13 13:07:37

2

幾件事情:

  1. 提供給PostAsync字典只填充字段請求主體,並因此增加的Content-Type在那裏沒有任何效果
  2. 文件資源平均將使用需要內容的UploadAsync方法創建。我不相信有一個API可以調用來告訴服務創建一個空白的Office文檔。
+0

我成功地使用UploadAsync()在onedrive上傳word,excel和許多其他文檔。這裏是我如何調用方法的一個例子:「LiveOperationResult uploadResult = await connectedClient.UploadAsync(folderId,fileName,fileStream,OverwriteOption.Overwrite);」其中folderId =「me/skydrive」,fileName =「Document.docx」,filestream =我從計算機中選取的文件的inputStream,它在onedrive中創建了doc文件。我在「fileStream」中自動設置了contentType,所以我認爲這應該是一種手動設置它的方法。 – CalinCosmin 2014-12-20 14:42:10

1

我還有別的東西。我創建了一個HttpWebRequest並設置了一些參數。現在它將文件作爲docx創建到我的onedrive帳戶,但是當我嘗試從我的帳戶打開文件時,出現一條錯誤消息,它說「發生了什麼問題,我們無法打開文件」。該文件存在但無法打開。

我寫的代碼是這樣的。有什麼建議麼 ?

public async Task<ActionResult> CreateWordFile() 
{ 
    string body = "--A300x\r\n" 
      + "Content-Disposition: form-data; name=\"file\"; filename=\"csm.docx\"\r\n" 
      + "Content-Type: application/octet-stream\r\n" 
      + "\r\n" 
      + "This is some content\r\n" 
      + "\r\n" 
      + "--A300x--\r\n"; 

    byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(body); 
    Stream stream = new MemoryStream(fileBytes); 

    LiveLoginResult loginStatus = await authClient.InitializeWebSessionAsync(HttpContext); 
    if (loginStatus.Status == LiveConnectSessionStatus.Connected) 
    { 
     connectedClient = new LiveConnectClient(this.authClient.Session); 
     string url = "https://apis.live.net/v5.0/me/skydrive/files?access_token=" + this.authClient.Session.AccessToken; 


     HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(url); 
     httpWebRequest2.ContentType = "multipart/form-data; boundary=A300x"; 
     httpWebRequest2.Method = "POST"; 
     httpWebRequest2.KeepAlive = true; 
     httpWebRequest2.Credentials = System.Net.CredentialCache.DefaultCredentials; 
     httpWebRequest2.ContentLength = fileBytes.Length; 
     Stream stream2 = httpWebRequest2.GetRequestStream(); 
     stream2.Write(fileBytes, 0, fileBytes.Length); 
     WebResponse webResponse2 = httpWebRequest2.GetResponse(); 
     } 

    return View(); 
} 
1

我也找到了創建xlsx文件的答案。

public async Task<ActionResult> CreateExcelFile() 
     { 
      LiveLoginResult loginStatus = await authClient.InitializeWebSessionAsync(HttpContext); 
      if (loginStatus.Status == LiveConnectSessionStatus.Connected) 
      { 
       connectedClient = new LiveConnectClient(this.authClient.Session); 
       string url = "https://apis.live.net/v5.0/me/skydrive/files?access_token=" + this.authClient.Session.AccessToken; 

       XSSFWorkbook wb = new XSSFWorkbook(); 

       // create sheet 
       XSSFSheet sh = (XSSFSheet)wb.CreateSheet("Sheet1"); 
       // 10 rows, 10 columns 
       for (int i = 0; i < 100; i++) 
       { 
        var r = sh.CreateRow(i); 
        for (int j = 0; j < 100; j++) 
        { 
         r.CreateCell(j); 
        } 
       } 

       MemoryStream stream = new MemoryStream(); 
       wb.Write(stream); 
       stream.Dispose(); 

       var arrBites = stream.ToArray(); 

       MemoryStream newStream = new MemoryStream(arrBites); 

       var docFile = File(newStream, "application/octet-stream", "Excel.xlsx"); 
       MemoryStream streamFile = new MemoryStream(); 
       docFile.FileStream.Position = 0; 
       docFile.FileStream.CopyTo(streamFile); 

       var bites = streamFile.ToArray(); 
       Stream stream2 = new MemoryStream(bites); 

       try 
       { 
        LiveOperationResult getResult = await connectedClient.UploadAsync("me/skydrive", docFile.FileDownloadName, stream2, OverwriteOption.Overwrite); 
       } 
       catch (WebException ex) 
       { 

       } 
      } 
      return View(); 
     }