如何使用C#在Google驱动器中创建没有重复的文件夹?

时间:2019-05-02 09:29:16

标签: c# google-drive-api directory

我正在尝试在Google驱动器上创建一个文件夹,并检查该文件夹是否已存在。我是C#的新手,所以我写了一个代码来创建一个特定的文件夹,可以在其中上传我的CSV文件,但是每次我的应用程序运行时,它都会创建一个具有相同名称的重复文件夹,而现在我想弄清楚如何停下来。

 class GoogleApi
{
    private string[] Scopes = { DriveService.Scope.Drive };
    private string ApplicationName;
    private string FolderId;
    private string FileName;
    private string FilePath;
    private string ContentType;


    public GoogleApi(string fileName, string filePath)
    {
        ApplicationName = "MantisToDrive";
        ContentType = "text/csv";
        FileName = fileName;
        FilePath = filePath;


    }

    public void Upload()
    {
        UserCredential credential = GetCredentials();
        DriveService service = GetDriveService(credential);
        FolderId = CreateFolderToDrive(service, "MantisData");
        UploadFileToDrive(service, FileName, FilePath, ContentType);

    }

    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))
        {
            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;
    }

    private string UploadFileToDrive(DriveService service, string fileName, string filePath, string contentType)
    {
        var fileMatadata = new Google.Apis.Drive.v3.Data.File();
        fileMatadata.Name = fileName;
        fileMatadata.Parents = new List<string> { FolderId };

        FilesResource.CreateMediaUpload request;

        using (var stream = new FileStream(filePath, FileMode.Open))
        {
            request = service.Files.Create(fileMatadata, stream, contentType);              
            //service.Files.Delete(fileName).Execute();
            request.Upload();              
        }
        var file = request.ResponseBody;
        return file.Id;
    }

    // creating folder in google drive to store CSV 

    public static string CreateFolderToDrive(DriveService service, string folderName)
    {
        bool exists = Exists(service,folderName);
        if (exists)
            return $"Sorry but the file {folderName} already exists!";

        var file = new Google.Apis.Drive.v3.Data.File();
        file.Name = folderName;
        file.MimeType = "application/vnd.google-apps.folder";
        var request = service.Files.Create(file);
        request.Fields = "id";
        var result = request.Execute();
        return result.Id;
    }
    private static bool Exists(DriveService service, string name)
    {
        var listRequest = service.Files.List();
        listRequest.PageSize = 100;
        listRequest.Q = $"trashed = false and name contains '{name}' and 'root' in parents";
        listRequest.Fields = "files(name)";
        var files = listRequest.Execute().Files;

        foreach (var file in files)
        {
            if (name == file.Name)
                return true;
        }
        return false;
    }


}

1 个答案:

答案 0 :(得分:0)

这应该可行(检查文件夹是否在您的根文件夹中。如果不存在,该方法将创建一个文件夹):

    public static string CreateFolder(string folderName)
    {
        bool exists = Exists(folderName);
        if (exists)
            return $"Sorry but the file {folderName} already exists!";

        var file = new Google.Apis.Drive.v3.Data.File();
        file.Name = folderName;
        file.MimeType = "application/vnd.google-apps.folder";
        var request = service.Files.Create(file);
        request.Fields = "id";
        return request.Execute().Id;
    }
    private static bool Exists(string name)
    {
        var listRequest = service.Files.List();
        listRequest.PageSize = 100;
        listRequest.Q = $"trashed = false and name contains '{name}' and 'root' in parents";
        listRequest.Fields = "files(name)";
        var files = listRequest.Execute().Files;

        foreach (var file in files)
        {
            if (name == file.Name)
                return true;
        }
        return false;
    }

以防将来有人从这里来,并且pastebin链接已死。您可以通过以下方式将文件上传到Google驱动器:

    public static async Task UploadFileAsync(string fileName)
    {
        var file = new Google.Apis.Drive.v3.Data.File();
        file.Name = Path.GetFileName(fileName);
        file.Parents = new List<string> {folderID};

        byte[] byteArray = System.IO.File.ReadAllBytes(fileName);
        using (System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray))
        {
            await service.Files.Create(file, stream, "some mime type").UploadAsync();
        }

    }