从 C# 以编程方式创建文件到 Onedrive

本文关键字:文件 Onedrive 创建 方式 编程 | 更新日期: 2023-09-27 18:34:39

我想创建一个文档,docx,pptx或excel文件从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();
}

编辑:我得到的错误是这个:

"标头'内容类型'缺少必需的参数:"边界"。说明:执行当前 Web 请求期间发生未经处理的异常。请查看堆栈跟踪,了解有关错误及其在代码中起源位置的详细信息。异常详细信息:Microsoft.Live.LiveConnectException:标头"内容类型"缺少必需参数:"边界"。

从 C# 以编程方式创建文件到 Onedrive

有几件事:

  1. 提供给 PostAsync 的字典仅填充请求正文中的字段,因此在其中添加内容类型没有任何影响
  2. 文件资源意味着使用 UploadAsync 方法创建,该方法需要内容。我不相信您可以调用一个 API 来告诉服务创建空白的 Office 文档。

我还有其他东西。我创建了一个HttpWebRequest,并设置了一些参数。现在它将文件创建到我的 onedrive 帐户作为 docx,但是当我尝试从我的帐户打开文件时,会出现一条错误消息,它说"发生了错误。我们无法打开文件"。该文件存在,但无法打开。

我写的代码是这样的。有什么建议吗?

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();
}
最后,

我从 c# 创建一个 docx 文件。我把解决方案放在这里(该方法中的代码没有重构,因此可以在 severeal 方法中拆分(。

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");
}

我也知道创建一个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();
        }