如何在共享的Google驱动器而不是默认驱动器(我的驱动器)中创建目录并上传文件?

时间:2019-06-28 08:38:10

标签: c# file-upload google-drive-team-drive create-directory

我正在尝试使用不同的项目名称从数据库中获取数据并动态创建目录到Gooogle驱动器,并将CSV文件上传到相应的目录中,到目前为止,我没有问题,但是现在当我的项目上线时,客户端要求我创建目录在共享的Google云端硬盘中,而不是默认驱动器中,即“我的云端硬盘”,我不知道该怎么做。

我包含了我使用的代码-预先感谢您的任何帮助

private DriveService GetDriveService(UserCredential credential)
{
        return new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = ApplicationName,
        });
}

//verify User Credentials using client_secret.json file ...
private UserCredential GetCredentials()
{
        UserCredential credential;

        using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) // passing credentials which stored in Client_secret.json
        {
            string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json");

            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                "user",
                CancellationToken.None,
                new FileDataStore(credPath, true)).Result;
        }

        return credential;
}

// Method to upload CSV file to Drive and if File exist Update it instead creating one ..
private string UploadFileToDrive(DriveService service, string fileName, string filePath, string contentType, string foldername)
{
        string fileId = getFileIdByName(service, fileName, foldername);

        try
        {
            if (!String.IsNullOrWhiteSpace(fileId))
            {
                var fileMatadata = new Google.Apis.Drive.v3.Data.File();
                fileMatadata.Name = Path.GetFileName(fileName);

                fileMatadata.MimeType = "application/vnd.google-apps.file"; //"application/vnd.google-apps.spreadsheet"; 
                ;
                byte[] byteArray = System.IO.File.ReadAllBytes(filePath);
                System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);

                FilesResource.UpdateMediaUpload requestUpdate = new FilesResource.UpdateMediaUpload(service, fileMatadata, fileId, stream, contentType);
                requestUpdate.Upload();                   
            }
            else
            {
                var fileMatadata = new Google.Apis.Drive.v3.Data.File();
                fileMatadata.Name = Path.GetFileName(fileName);
                fileMatadata.Parents = new List<string> { FolderId };

                fileMatadata.MimeType = "application/vnd.google-apps.file";
                FilesResource.CreateMediaUpload request;
                using (System.IO.FileStream stream = new FileStream(filePath, FileMode.Open))
                {
                    request = service.Files.Create(fileMatadata, stream, contentType);
                    request.Upload();
                }

                var file = request.ResponseBody;
            }
        }
        catch (FileNotFoundException ex)
        {
            MessageBox.Show(ex.Message);
        }

        return fileId;
}

//Call to fucntion GetFolderById to test if folder exist 
private static string CreateFolderToDrive(DriveService service, string folderName)
{
        string exists = GetFolderIdById(service, id: folderName);
        return exists;
}

//Getting FileId of the file which is on google Drive 
private string getFileIdByName(DriveService service, string name, string folderName)
{
        string id = string.Empty;

        try
        {
            //folderName = FolderId;
            FilesResource.ListRequest listRequest = service.Files.List();
            listRequest.PageSize = 100;
            listRequest.Q = $"name contains '" + name + "' and trashed = false and parents= '" + folderName + "'";
            var files = listRequest.Execute().Files;

            foreach (var file in files)
            {
                id = file.Id;
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }

        return id;
}

// Method to get Folder ID From Google Drive 
private static string GetFolderIdById(DriveService service, string id)
{
        FilesResource.ListRequest listRequest = service.Files.List();
        listRequest.PageSize = 10;
        listRequest.Q = $"mimeType = 'application/vnd.google-apps.folder' and name = '{id}' and trashed = false ";
        listRequest.Fields = "files(id)";
        var files = listRequest.Execute().Files;

        if (files != null && files.Count > 0)
        {
            foreach (var file in files)
            {
                id = file.Id;
                return id;
            }
        }
        // if folder not found on Google Drive we create one here and return its id 
        else
        {
            var file = new Google.Apis.Drive.v3.Data.File();
            file.Name = id;
            file.MimeType = "application/vnd.google-apps.folder";
            var request = service.Files.Create(file);
            request.Fields = "id";
            return request.Execute().Id;
        }

        return id;
}

0 个答案:

没有答案