Prevent duplicate folder creation in Google Drive using C#

I need help with my C# application that connects to Google Drive API. Every time I run my program, it makes a new folder with the same name instead of using the existing one.

class DriveManager
{
    private string[] ApiScopes = { DriveService.Scope.Drive };
    private string AppName;
    private string DirectoryId;
    private string DocumentName;
    private string DocumentPath;
    private string FileType;

    public DriveManager(string docName, string docPath)
    {
        AppName = "DataUploader";
        FileType = "text/csv";
        DocumentName = docName;
        DocumentPath = docPath;
    }

    public void StartUpload()
    {
        UserCredential creds = AuthenticateUser();
        DriveService driveClient = InitializeDriveService(creds);
        DirectoryId = MakeDirectory(driveClient, "ReportsFolder");
        UploadDocument(driveClient, DocumentName, DocumentPath, FileType);
    }

    private DriveService InitializeDriveService(UserCredential creds)
    {
        return new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = creds,
            ApplicationName = AppName,
        });
    }

    private UserCredential AuthenticateUser()
    {
        UserCredential userCreds;
        using (var fileStream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
        {
            string credsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            credsPath = Path.Combine(credsPath, ".auth/drive-app.json");

            userCreds = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(fileStream).Secrets,
                ApiScopes,
                "user",
                CancellationToken.None,
                new FileDataStore(credsPath, true)).Result;
        }
        return userCreds;
    }

    private string UploadDocument(DriveService client, string docName, string docPath, string mimeType)
    {
        var docMetadata = new Google.Apis.Drive.v3.Data.File();
        docMetadata.Name = docName;
        docMetadata.Parents = new List<string> { DirectoryId };

        FilesResource.CreateMediaUpload uploadRequest;
        using (var fileStream = new FileStream(docPath, FileMode.Open))
        {
            uploadRequest = client.Files.Create(docMetadata, fileStream, mimeType);
            uploadRequest.Upload();
        }
        var uploadedFile = uploadRequest.ResponseBody;
        return uploadedFile.Id;
    }

    public static string MakeDirectory(DriveService client, string dirName)
    {
        bool folderExists = CheckIfExists(client, dirName);
        if (folderExists)
            return $"Directory {dirName} is already there!";

        var newFolder = new Google.Apis.Drive.v3.Data.File();
        newFolder.Name = dirName;
        newFolder.MimeType = "application/vnd.google-apps.folder";
        var createRequest = client.Files.Create(newFolder);
        createRequest.Fields = "id";
        var response = createRequest.Execute();
        return response.Id;
    }

    private static bool CheckIfExists(DriveService client, string folderName)
    {
        var searchRequest = client.Files.List();
        searchRequest.PageSize = 100;
        searchRequest.Q = $"trashed = false and name contains '{folderName}' and 'root' in parents";
        searchRequest.Fields = "files(name)";
        var foundFiles = searchRequest.Execute().Files;

        foreach (var foundFile in foundFiles)
        {
            if (folderName == foundFile.Name)
                return true;
        }
        return false;
    }
}

The issue is that my folder checking logic does not work properly. Can someone tell me what I am doing wrong? I want to reuse the same folder if it exists instead of making duplicates.

Your CheckIfExists method only returns true/false but doesn’t give you the folder ID when it finds one. That’s the issue. Instead of returning a boolean, make it return the actual folder ID (or null if nothing’s found). When I hit this same problem, I rewrote the method to return the ID directly. Then in MakeDirectory, just check if you got null back before creating a new folder. Also, add the folder mime type to your query so it doesn’t match files with the same name: “trashed = false and name = ‘{folderName}’ and mimeType = ‘application/vnd.google-apps.folder’ and ‘root’ in parents”. I switched ‘contains’ to ‘=’ for exact matching too.

your MakeDirectory method returns a string message when it finds an existing folder, not the actual folder ID. that’s why it keeps making new ones. just return the folder ID instead of the text message.

Your MakeDirectory method is mixing up return types - it sends back a string message when a folder exists, but UploadDocument expects an ID. That’s what’s breaking things.

Here’s the fix: Make CheckIfExists return the actual folder ID when it finds a match, and null when it doesn’t. Then MakeDirectory just needs to check if you got null back before creating anything new.

Also, switch that ‘contains’ in your search query to ‘=’ - otherwise you’ll match folders with similar names instead of exact matches.