我正在尝试从谷歌驱动器下载文件,这是我的代码
private static IAuthenticator CreateAuthenticator()
{
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
provider.ClientIdentifier = ClientCredentials.CLIENT_ID;
provider.ClientSecret = ClientCredentials.CLIENT_SECRET;
return new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
}
public static System.IO.Stream DownloadFile(
IAuthenticator authenticator, Google.Apis.Drive.v2.Data.File file)
{
if (!String.IsNullOrEmpty(file.DownloadUrl))
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
new Uri(file.DownloadUrl));
authenticator.ApplyAuthenticationToRequest(request);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
return response.GetResponseStream();
}
else
{
Console.WriteLine(
"An error occurred: " + response.StatusDescription);
return null;
}
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
return null;
}
}
else
{
// The file doesn't have any content stored on Drive.
return null;
}
}
在.aspx页面代码中 { System.IO.Stream stream = Utilities.DownloadFile(CreateAuthenticator(),FIle);
//Convert the stream to an array of bytes.
System.IO.BinaryReader br = new System.IO.BinaryReader(stream);
Byte[] byteArray = br.ReadBytes((int)stream.Length);
显示此流不支持搜索操作。
哪里是错误 谢谢你....
答案 0 :(得分:0)
如果您只是想下载文件,则无需搜索该文件。你应该做的只是阅读流,即通过DownloadFile API方法,并将其传递给浏览器。我已通过以下代码启用它:
public FileResult DownloadFile(string fileId)
{
DriveService service = Session["service"] as DriveService;
Google.Apis.Drive.v2.Data.File file = service.Files.Get(fileId).Fetch();
System.IO.Stream data = new GDriveRepository(Utils.ReturnIAuth((GoogleAuthenticator)Session["Gauthenticator"])).DownloadFile(file.DownloadUrl);
return File(data, System.Net.Mime.MediaTypeNames.Application.Octet, file.Title);
}