Preventing duplicate folder creation when using Google Drive API with C#

Need help with C# Google Drive integration

I’m working on a C# application that uploads CSV files to Google Drive. The problem is that every time I run my program, it creates a new folder with the same name instead of using the existing one. I have written some code to check if the folder exists before creating it, but something is not working right.

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 ExecuteUpload()
    {
        UserCredential auth = AuthenticateUser();
        DriveService driveClient = InitializeDriveService(auth);
        DirectoryId = SetupDirectory(driveClient, "DataStorage");
        TransferFile(driveClient, DocumentName, DocumentPath, FileType);
    }

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

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

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

    private string TransferFile(DriveService driveClient, string docName, string docPath, string fileType)
    {
        var fileProperties = new Google.Apis.Drive.v3.Data.File();
        fileProperties.Name = docName;
        fileProperties.Parents = new List<string> { DirectoryId };

        FilesResource.CreateMediaUpload uploadRequest;

        using (var fileStream = new FileStream(docPath, FileMode.Open))
        {
            uploadRequest = driveClient.Files.Create(fileProperties, fileStream, fileType);
            uploadRequest.Upload();
        }
        var uploadedFile = uploadRequest.ResponseBody;
        return uploadedFile.Id;
    }

    public static string SetupDirectory(DriveService driveClient, string directoryName)
    {
        bool folderExists = CheckDirectoryExists(driveClient, directoryName);
        if (folderExists)
            return $"Directory {directoryName} is already present!";

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

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

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

Can someone help me figure out why the duplicate check is not working properly?

Your CheckDirectoryExists method has a flawed query that’s causing the duplicate folder issue. The problem is with name contains '{directoryName}' - this will match partial names and potentially return false positives. You should use name = '{directoryName}' for exact matching instead. Additionally, your search query is missing the mimeType filter to specifically look for folders. Try changing the query to: trashed = false and name = '{directoryName}' and mimeType = 'application/vnd.google-apps.folder' and 'root' in parents. I encountered similar behavior when working with Drive API integration last year - the contains operator was matching folders with names like “DataStorage_backup” when I was looking for “DataStorage”. Also, make sure you’re handling the case where CheckDirectoryExists returns true but SetupDirectory returns a string message instead of the folder ID, which will break your file upload process.

I spotted the issue in your SetupDirectory method - there’s a type mismatch that’s causing the problem. When CheckDirectoryExists returns true, you’re returning a string message instead of the actual folder ID, but your TransferFile method expects DirectoryId to be a valid folder identifier. The fix is straightforward: modify your CheckDirectoryExists method to return the folder ID when found, and update SetupDirectory accordingly. Change the searchRequest.Fields to “files(id, name)” so you can retrieve the ID, then return foundFile.Id instead of just true when the folder exists. I ran into this exact same issue last year when building a similar upload tool. The Google Drive API silently accepts invalid parent IDs and just creates folders in the root directory, which explains why you keep getting duplicates. Also consider adding the mimeType filter to your search query to ensure you’re only matching actual folders, not files with the same name.

quick fix - your SetupDirectory method returns different data types which breaks everything. when folder exists it returns a string message but when creating new folder it returns ID. thats why your upload always fails silently and creates new folders. just modify CheckDirectoryExists to return the actual folder id instead of boolean, then SetupDirectory can always return an id. been there, google drive api is tricky like that