Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用Google Drive API将文件上载到Google Drive时OutOfMemoryException_C#_Http_Google Drive Api_Bytearray - Fatal编程技术网

C# 使用Google Drive API将文件上载到Google Drive时OutOfMemoryException

C# 使用Google Drive API将文件上载到Google Drive时OutOfMemoryException,c#,http,google-drive-api,bytearray,C#,Http,Google Drive Api,Bytearray,这是一个web应用程序。我打算使用GoogleDrive API将大型文件上传到GoogleDrive。我的代码适用于较小的文件。但当涉及到较大的文件时,就会出现错误 我搜索了很多,但找不到工作的解决方案,有些问题没有答案 将文件转换为字节[]的代码部分出错 byte[] fileData = System.IO.File.ReadAllBytes(dir); 对于web.config我试图更改请求长度,但对于大型文件无效 <httpRuntime targetFramework="4.

这是一个web应用程序。我打算使用GoogleDrive API将大型文件上传到GoogleDrive。我的代码适用于较小的文件。但当涉及到较大的文件时,就会出现错误

我搜索了很多,但找不到工作的解决方案,有些问题没有答案

将文件转换为字节[]的代码部分出错

byte[] fileData = System.IO.File.ReadAllBytes(dir);
对于web.config我试图更改请求长度,但对于大型文件无效

<httpRuntime targetFramework="4.5" executionTimeout="520000" maxRequestLength="920000"  />

有人能解决这个问题吗?提前谢谢

下面是完整的代码


使用系统;
使用系统诊断;
使用DotNetOpenAuth.OAuth2;
使用Google.api.Authentication.OAuth2;
使用Google.api.Authentication.OAuth2.DotNetOpenAuth;
使用Google.api.Drive.v2;
使用Google.api.Drive.v2.Data;
使用Google.api.Util;
使用ASPSnippets.GoogleAPI;
使用System.Web.Script.Serialization;
使用System.Web;
使用System.Collections.Generic;
使用System.Net.Http;
Net系统;
使用System.IO;
运用系统反思;
名称空间GoogleDriveAutoUpdate
{
公共部分类GoogleDriveSample:System.Web.UI.Page
{
静态int flagUpdateFile;
受保护字符串[]dirs=Directory.GetFiles(@“C:\Users\RNKP74\Desktop\GoogleDrive”);
受保护的无效页面加载(对象发送方、事件参数e)
{
GoogleConnect.ClientId=“”;
GoogleConnect.ClientSecret=“”;
GoogleConnect.RedirectUri=Request.Url.AbsoluteUri.Split(“?”)[0];
GoogleConnect.API=EnumAPI.Drive;
if(string.IsNullOrEmpty(Request.QueryString[“code”]))
GoogleConnect.Authorize(“https://www.googleapis.com/auth/drive.file");
如果(flagUpdateFile==0)
上传文件();
}
受保护的HttpPostedFile ConstructHttpPostedFile(字节[]数据,字符串文件名,字符串contentType=null)
{
//获取System.Web程序集引用
Assembly systemWebAssembly=typeof(HttpPostedFileBase).Assembly;
//获取我们需要的两种内部类型的类型
键入typeHttpRawUploadedContent=systemWebAssembly.GetType(“System.Web.HttpRawUploadedContent”);
键入typeHttpInputStream=systemWebAssembly.GetType(“System.Web.HttpInputStream”);
//准备我们想要的构造器的签名。
Type[]uploadedParams={typeof(int),typeof(int)};
Type[]streamParams={typeHttpRawUploadedContent,typeof(int),typeof(int)};
Type[]参数={typeof(string)、typeof(string)、typeHttpInputStream};
//创建HttpRawUploadedContent实例
object uploadedContent=类型HttpRawUploadedContent
.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance,null,uploadedParams,null)
.Invoke(新对象[]{data.Length,data.Length});
//调用AddBytes方法
类型HttpRawUploadedContent
.GetMethod(“AddBytes”,BindingFlags.NonPublic | BindingFlags.Instance)
.Invoke(uploadedContent,新对象[]{data,0,data.Length});
//如果要使用返回的内容(即保存),这是必需的
类型HttpRawUploadedContent
.GetMethod(“DoneAddingBytes”,BindingFlags.NonPublic | BindingFlags.Instance)
.Invoke(uploadedContent,null);
//创建HttpInputStream实例
对象流=(流)类型HttpInputStream
.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance,null,streamParams,null)
.Invoke(新对象[]{uploadedContent,0,data.Length});
//创建HttpPostedFile实例
HttpPostedFile postedFile=(HttpPostedFile)类型(HttpPostedFile)
.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance,null,parameters,null)
.Invoke(新对象[]{filename,contentType,stream});
返回postedFile;
}
受保护的无效上载文件()
{
int successCount=0;
HttpFileCollection MyFileCollection=Request.Files;
响应。写入(“总数文件=“+dirs.Length+”
); foreach(dirs中的字符串dir) { byte[]fileData=System.IO.File.ReadAllBytes(dir); 字符串文件名=Path.GetFileName(dir); flagUpdateFile=1; //内容类型为空 会话[“文件”]=ConstructHttpPostedFile(文件数据,文件名); //从googleapi返回令牌 如果(!string.IsNullOrEmpty(Request.QueryString[“code”])&&flagUpdateFile==1) { 字符串代码=Request.QueryString[“code”]; 字符串json=GoogleConnect.PostFile(代码,(HttpPostedFile)会话[“文件”],“”); flagUpdateFile=0; System.IO.File.Delete(dir); successCount++; } if(Request.QueryString[“error”]=“访问被拒绝”) { RegisterClientScriptBlock(this.GetType(),“警报”,“警报('Access denied')”,true); Write(“拒绝访问,检查您的授权重定向URI!”); } HttpContext.Current.Session.Remove(“文件”); HttpContext.Current.Session.about(); } Response.Write(“上传的文件总数=“+successCount”); 成功计数=0; 响应。写入(
如果数字相同,则成功); } } }
我承认我不知道GoogleDrive API,但您的代码似乎非常复杂。为什么要进行反射,为什么要对每个文件进行反射?你为什么要把它装在箱子里
using System;
using System.Diagnostics;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Drive.v2;
using Google.Apis.Drive.v2.Data;
using Google.Apis.Util;
using ASPSnippets.GoogleAPI;
using System.Web.Script.Serialization;
using System.Web;
using System.Collections.Generic;
using System.Net.Http;
using System.Net;
using System.IO;
using System.Reflection;

namespace GoogleDriveAutoUpdate
{
    public partial class GoogleDriveSample : System.Web.UI.Page
    {
        static int flagUpdateFile;
        protected string[] dirs = Directory.GetFiles(@"C:\Users\RNKP74\Desktop\GoogleDrive");


        protected void Page_Load(object sender, EventArgs e)
        {
            GoogleConnect.ClientId = "";
            GoogleConnect.ClientSecret = "";
            GoogleConnect.RedirectUri = Request.Url.AbsoluteUri.Split('?')[0];
            GoogleConnect.API = EnumAPI.Drive;

            if (string.IsNullOrEmpty(Request.QueryString["code"]))
                GoogleConnect.Authorize("https://www.googleapis.com/auth/drive.file");

            if (flagUpdateFile == 0)
                UploadFile();
        }

        protected HttpPostedFile ConstructHttpPostedFile(byte[] data, string filename, string contentType = null)
        {
            // Get the System.Web assembly reference
            Assembly systemWebAssembly = typeof(HttpPostedFileBase).Assembly;
            // Get the types of the two internal types we need
            Type typeHttpRawUploadedContent = systemWebAssembly.GetType("System.Web.HttpRawUploadedContent");
            Type typeHttpInputStream = systemWebAssembly.GetType("System.Web.HttpInputStream");

            // Prepare the signatures of the constructors we want.
            Type[] uploadedParams = { typeof(int), typeof(int) };
            Type[] streamParams = { typeHttpRawUploadedContent, typeof(int), typeof(int) };
            Type[] parameters = { typeof(string), typeof(string), typeHttpInputStream };

            // Create an HttpRawUploadedContent instance
            object uploadedContent = typeHttpRawUploadedContent
                .GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, uploadedParams, null)
                .Invoke(new object[] { data.Length, data.Length });

            // Call the AddBytes method
            typeHttpRawUploadedContent
                .GetMethod("AddBytes", BindingFlags.NonPublic | BindingFlags.Instance)
                .Invoke(uploadedContent, new object[] { data, 0, data.Length });

            // This is necessary if you will be using the returned content (ie to Save)
            typeHttpRawUploadedContent
                .GetMethod("DoneAddingBytes", BindingFlags.NonPublic | BindingFlags.Instance)
                .Invoke(uploadedContent, null);

            // Create an HttpInputStream instance
            object stream = (Stream)typeHttpInputStream
                .GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, streamParams, null)
                .Invoke(new object[] { uploadedContent, 0, data.Length });

            // Create an HttpPostedFile instance
            HttpPostedFile postedFile = (HttpPostedFile)typeof(HttpPostedFile)
                .GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, parameters, null)
                .Invoke(new object[] { filename, contentType, stream });

            return postedFile;
        }

        protected void UploadFile()
        {
            int successCount = 0;
            HttpFileCollection MyFileCollection = Request.Files;
            Response.Write("Total number file = " + dirs.Length + "<br/>");

            foreach (string dir in dirs)
            {

                byte[] fileData = System.IO.File.ReadAllBytes(dir);
                string fileName = Path.GetFileName(dir);
                flagUpdateFile = 1;
                //Content Type is null
                Session["File"] = ConstructHttpPostedFile(fileData, fileName);

                //Token return from Google API
                if (!string.IsNullOrEmpty(Request.QueryString["code"]) && flagUpdateFile == 1)
                {
                    string code = Request.QueryString["code"];
                    string json = GoogleConnect.PostFile(code, (HttpPostedFile)Session["File"], "");
                    flagUpdateFile = 0;
                    System.IO.File.Delete(dir);
                    successCount++;
                }

                if (Request.QueryString["error"] == "access_denied")
                {
                    ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('Access denied.')", true);
                    Console.Write("Access denied,check your Authorized redirect URIs!");
                }

                HttpContext.Current.Session.Remove("File");
                HttpContext.Current.Session.Abandon();

            }
            Response.Write("Total file uploaded = " + successCount);
            successCount = 0;
            Response.Write("<span id='Label1' style='color:red'><br/>Sucess if the number is identical</span>");

        }


    }
}
<configuration>
  <runtime>
    <gcAllowVeryLargeObjects enabled="true" />
  </runtime>
</configuration>
true: Arrays greater than 2 GB in total size are enabled on 64-bit platforms.