How to search for a file by file name

Daniel Man 0 Reputation points
2024-11-25T00:38:19.3566667+00:00

What is the correct syntax to search for a file using a file name for the below call?

GraphClient.Drives[_Drive.Id].SearchWithQ("q").GetAsSearchWithQGetResponseAsync();

I cannot find any documentation on how to do this.

Thanks for your help

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,084 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Jiale Xue - MSFT 47,196 Reputation points Microsoft Vendor
    2024-11-25T01:57:43.89+00:00

    Hi @Daniel Mande ,Welcome to Microsoft Q&A,

    In the .NET SDK for the Microsoft Graph API, the SearchWithQ method is used to search for files or folders in a OneDrive or SharePoint drive.

    // File name for search
    var fileName = "file name or part of the name";
    
    try
    {
        // Call SearchWithQ method to search for files
        var searchResults = await GraphClient
        .Drives[_Drive.Id] // Target drive ID
        .Root // Search in the root directory (or specify a subdirectory)
        .SearchWithQ(fileName)
        .Request()
        .GetAsync();
    
        // Traverse search results
        foreach (var item in searchResults)
        {
            Console.WriteLine($"Found file: {item.Name}, file ID: {item.Id}");
        }
    }
    catch (ServiceException ex)
    {
        // Error handling
        Console.WriteLine($"Search failed: {ex.Message}");
    }
    

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.