将来自Google Drive Apis v2的ParentReference迁移到C#.Net中的v3

时间:2017-05-14 14:02:19

标签: c# .net google-api google-drive-api

在此处阅读Gdrive.v3 SDK上的Google迁移信息后:https://developers.google.com/drive/v3/web/migration,我仍然不确定如何正确设置文件的ParentReference(到根文件夹)。目前在v2中,这是通过以下方式完成的:

private string UploadToGDrive( Google.Apis.Drive.v3.DriveService service, string uploadFile, string parent)
{
    var body = new Google.Apis.Drive.v3.Data.File
    {
        Name = Path.GetFileName(uploadFile),
        Description = uploadFile,
        MimeType = GetMimeType(uploadFile),
        Parents = new List<ParentReference> {new ParentReference {Id = parent}}
    };
}

private string GetMimeType(string fileName)
{
    var mimeType = "application/unknown";
    var extension = Path.GetExtension(fileName);
    if (extension == null) return mimeType;
    var ext = extension.ToLower();
    var regKey = Registry.ClassesRoot.OpenSubKey(ext);
    if (regKey?.GetValue("Content Type") != null) return mimeType;
    if (regKey != null) mimeType = regKey.GetValue("Content Type").ToString();
    return mimeType;
}

2 个答案:

答案 0 :(得分:1)

正如文件中所述 - Inserting a file in a folder

  

要在特定文件夹中插入文件,请在文件的parents属性中指定正确的ID,如下所示:

var folderId = "0BwwA4oUTeiV1TGRPeTVjaWRDY1E";
var fileMetadata = new File()
{
    Name = "photo.jpg",
    Parents = new List<string>
    {
        folderId
    }
};
FilesResource.CreateMediaUpload request;
using (var stream = new System.IO.FileStream("files/photo.jpg",
    System.IO.FileMode.Open))
{
    request = driveService.Files.Create(
        fileMetadata, stream, "image/jpeg");
    request.Fields = "id";
    request.Upload();
}
var file = request.ResponseBody;
Console.WriteLine("File ID: " + file.Id);

希望这有帮助。

答案 1 :(得分:0)

我必须监督这个...这只是意味着在我的情况下取代

var body = new Google.Apis.Drive.v3.Data.File
{
    Name = Path.GetFileName(uploadFile),
    Description = uploadFile,
    MimeType = GetMimeType(uploadFile),
    Parents = new List<ParentReference> {new ParentReference {Id = parent}}
};

var body = new Google.Apis.Drive.v3.Data.File
{
    Name = Path.GetFileName(uploadFile),
    Description = uploadFile,
    MimeType = GetMimeType(uploadFile),
    Parents = new List<string> {parent}
};

(我已添加此作为答案,因为它是为了征求意见)。