2016-09-27 8 views
0

質問:一括ファイルのダウンロード - ドライブAPI .NET

どのように私のバックアップツールにfileidで記録されたすべてのファイルをダウンロードするように指示できますか?

私が使用している方法は、C#の/である。NET https://developers.google.com/drive/v3/web/manage-downloads#examples

私は、退屈な詳細を惜しまと(まあ、アプリサービスAPIを使用して)各ユーザーとして一度に私のプログラムのログの一部を言いますよすべてのファイルのfileIdsを取得し、フラットテキストファイルに記録します。私のプログラムはそのフラットテキストファイルを開き、そのユーザーのために記録された各fileIdのダウンロードを開始しますが、問題は次のとおりです。ファイルの新しい接続を開き、ファイルが終了するのを待って新しいファイルIDを取得し、すべてのプロセスをやり直すあまり効率的ではありません。

私はかなり逐語(私はすぐにつかみ、そのMIMEタイプをエクスポートすることで少しvarsの変更なので、最初の3行は議論の余地がある)コピーされたGoogleの例、:

var fileId = "0BwwA4oUTeiV1UVNwOHItT0xfa2M"; 
var request = driveService.Files.Get(fileId); 
var stream = new System.IO.MemoryStream(); 

// Add a handler which will be notified on progress changes. 
// It will notify on each chunk download and when the 
// download is completed or failed. 
request.MediaDownloader.ProgressChanged += 
    (IDownloadProgress progress) => 
{ 
    switch(progress.Status) 
    { 
     case DownloadStatus.Downloading: 
     { 
      Console.WriteLine(progress.BytesDownloaded); 
      break; 
     } 
     case DownloadStatus.Completed: 
     { 
      Console.WriteLine("Download complete."); 
      break; 
     } 
     case DownloadStatus.Failed: 
     { 
      Console.WriteLine("Download failed."); 
      break; 
     } 
    } 
}; 
request.Download(stream); 

は、任意の方法がありますI私のプログラムは、1つの大きな握手でユーザーのために知っているすべてのファイルをダウンロードできるように、これを合理化することができますか?これが理にかなってほしい。

お時間をお待ちしております。

--Mike

---私はうまくいけば、私は何を探していますがより理にかなっているように、詳細を追加したいEDIT ---

だから何です次のコードで起こっている:私は私がfileId [0]としてフラットテキストファイルから持っているファイルタイプをエクスポートさせる "要求"を作成しています、そして "mimetype"は配列にfileId [ 1]を参照してください。) プログラムの速度を落としているのは、それぞれの "BuildService"リクエストを構築することです私は各ファイルのために私。

foreach (var file in deltafiles) 
{ 
    try 
    { 
    if (bgW.CancellationPending) 
    { 
     stripLabel.Text = "Backup canceled!"; 
     e.Cancel = true; 
     break; 
     } 
     DateTime dt = DateTime.Now; 
     string[] foldervalues = File.ReadAllLines(savelocation + "folderlog.txt"); 
     cnttototal++; 
     bgW.ReportProgress(cnttototal); 
     // Our file is a CSV. Column 1 = file ID, Column 2 = File name 
     var values = file.Split(','); 

     string fileId = values[0]; 
     string fileName = values[1]; 
     string mimetype = values[2]; 
     mimetype = mimetype.Replace(",", "_"); 
     string folder = values[3]; 
     int foundmatch = 0; 
     int folderfilelen = foldervalues.Count(); 

     fileName = fileName.Replace('\\', '_').Replace('/', '_').Replace(':', '_').Replace('!', '_').Replace('\'', '_').Replace('*', '_').Replace('#', '_').Replace('[', '_').Replace(']', '_'); 

     var request = CreateService.BuildService(user).Files.Export(fileId, mimetype); 

     //Default extensions for files. Not sure what this should be, so we'll null it for now. 
     string ext = null; 

     // Things get sloppy here. The reason we're checking MimeTypes 
     // is because we have to export the files from Google's format 
     // to a format that is readable by a desktop computer program 
     // So for example, the google-apps.spreadsheet will become an MS Excel file. 
     if (mimetype == mimeSheet || mimetype == mimeSheetRitz || mimetype == mimeSheetml) 
     { 
      request = CreateService.BuildService(user).Files.Export(fileId, exportSheet); 
      ext = ".xls"; 
     } 
     if (mimetype == mimeDoc || mimetype == mimeDocKix || mimetype == mimeDocWord) 
     { 
      request = CreateService.BuildService(user).Files.Export(fileId, exportDoc); 
      ext = ".docx"; 
     } 
     if (mimetype == mimePres || mimetype == mimePresPunch) 
     { 
      request = CreateService.BuildService(user).Files.Export(fileId, exportPres); 
      ext = ".ppt"; 
     } 
     if (mimetype == mimeForm || mimetype == mimeFormfb || mimetype == mimeFormDrawing) 
     { 
      request = CreateService.BuildService(user).Files.Export(fileId, exportForm); 
      ext = ".docx"; 
     } 
     // Any other file type, assume as know what it is (which in our case, will be a txt file) 
     // apply the mime type and carry on. 
     string dest = Path.Combine(savelocation, fileName + ext); 
     var stream = new System.IO.FileStream(dest, FileMode.Create, FileAccess.ReadWrite); 
     int oops = 0; 
     // Add a handler which will be notified on progress changes. 
     // It will notify on each chunk download and when the 
     // download is completed or failed. 

     request.MediaDownloader.ProgressChanged += 
     (IDownloadProgress progress) => 
     { 
      switch (progress.Status) 
      { 
       case DownloadStatus.Downloading: 
       { 
        throw new Exception("File may be corrupted."); 
        break; 
        } 
       case DownloadStatus.Completed: 
       { 
        Console.WriteLine("Download complete."); 
        break; 
       } 
       case DownloadStatus.Failed: 
       { 
        oops = 1; 
        logFile.WriteLine(fileName + " could not be downloaded. Possible Google draw/form OR bad name.\n"); 
        break; 
       } 
      } 
     }; 
     request.Download(stream); 
     stream.Close(); 
     stream.Dispose(); 

ドライブのサービスを構築する必要がないように、このプロセスを合理化する方法はありますか?ファイルをダウンロードするたびに?フラットなテキストプログラムが読み込むファイルは、だから私は真ん中の男をカットし、常に「foreachのを思い出さずにrequest.Download方法を養うことができどのような方法があり、MIMETYPE

FILEID、実際のファイル名に似ています"ステートメントを使用して、ファイルタイプをファイルシステムで読み取り可能なファイルとしてエクスポートしますか? (良い悲しみ、申し訳ありませんが、私はこれは多くのように聞こえることを知っています)

すべてのポインタが素晴らしいだろう!

答えて

0

チュートリアルGoogle Drive API with C# .net – Downloadをお試しください。これは、ファイルをダウンロードするコードがはるかに簡単です。また、ファイルをダウンロードするETAに影響する可能性のある断続的なインターネット接続のような他の要因もあります。

コードサンプル:_service.HttpClient.GetByteArrayAsyncを使用して

/// Download a file 
/// Documentation: https://developers.google.com/drive/v2/reference/files/get 
/// 

/// a Valid authenticated DriveService 
/// File resource of the file to download 
/// location of where to save the file including the file name to save it as. 
/// 
public static Boolean downloadFile(DriveService _service, File _fileResource, string _saveTo) 
{ 

if (!String.IsNullOrEmpty(_fileResource.DownloadUrl)) 
{ 
try 
{ 
var x = _service.HttpClient.GetByteArrayAsync(_fileResource.DownloadUrl); 
byte[] arrBytes = x.Result; 
System.IO.File.WriteAllBytes(_saveTo, arrBytes); 
return true; 
} 
catch (Exception e) 
{ 
Console.WriteLine("An error occurred: " + e.Message); 
return false; 
} 
} 
else 
{ 
// The file doesn't have any content stored on Drive. 
return false; 
} 
} 

我々はそれを私たちがダウンロードしたいファイルのダウンロードURLを渡すことができます。ファイルがダウンロードされると、そのファイルをディスクに書き込むという単純な問題です。

+0

ありがとうございました!私はリンクを感謝します:-)私はちょうど始めていたときに以前のことを参照しようとしましたが、v2がすぐに "EOL"になるようにsdk v3を駆動することにしました。 –

0

これは解決策ではありませんが、それでも半分の答えです(今のところです)。私は手袋を外して汚れた。

まず、自分のVSプロジェクトの中で最新のバージョンのナゲットgoogle apiパッケージを更新してからhttps://github.com/google/google-api-dotnet-clientに行き、fork/clonedしてGoogle.Apis.Drive.v3.csファイルをコンパイルしましたgoogle.apis.drive.v3.dll)、mimetypeはもはや読み込み専用ではなくなりました(getとsetを行うことができます;デフォルトではgetを許可しました)。

私は既にMIMEタイプを知っていたので、クライアントサービスをビルドする代わりに、MIMEタイプをリクエストに割り当てて、自分の人生を続けることができます。私はすでにそれが分かっています。

これはかなりうまくいかないが、これは本当に私を悩ませていた!

@ Mr.Rebotに戻って、あなたの助けと研究をもう一度感謝します! :-)

関連する問題